1. 引言
本节为非规范性内容。
图形处理单元(GPU)在个人计算领域中已成为实现丰富渲染和计算应用的关键。WebGPU 是一个为 Web 暴露 GPU 硬件能力的 API。该 API 从零开始设计,能够高效映射到(2014年之后的)原生 GPU API。WebGPU 与 WebGL 无关,也不直接针对 OpenGL ES。
WebGPU 将物理 GPU 硬件视为 GPUAdapter。它通过
GPUDevice
提供与适配器的连接,设备负责管理资源,并通过设备的 GPUQueue
执行命令。GPUDevice
可能拥有自己的高速存储器以供处理单元访问。GPUBuffer 和
GPUTexture
是由 GPU 内存支持的物理资源。GPUCommandBuffer
和 GPURenderBundle
是用户录制命令的容器。GPUShaderModule
包含 着色器代码。其他资源如 GPUSampler 或
GPUBindGroup
用于配置 GPU 如何使用物理资源。
GPU 通过 GPUCommandBuffer
编码的命令,通过 管线
执行,该管线是固定功能与可编程阶段的混合体。可编程阶段运行着色器,即专为 GPU 硬件设计的特殊程序。管线的大部分状态由 GPURenderPipeline
或 GPUComputePipeline
对象定义。未包含在这些 管线对象中的状态,则在命令编码阶段通过如 beginRenderPass()
或 setBlendConstant()
之类命令设置。
2. 恶意使用考量
本节为非规范性内容。 介绍了在 Web 上暴露此 API 所带来的风险。
2.1. 安全考量
WebGPU 的安全要求与 Web 一贯的要求相同,也是不可协商的。总体原则是:在所有命令到达 GPU 之前进行严格校验,确保页面只能操作自身数据。
2.1.1. 基于 CPU 的未定义行为
WebGPU 实现会将用户发起的工作量转换为目标平台特定的 API 命令。原生 API 规定了命令的有效用法(例如见 vkCreateDescriptorSetLayout),并且通常不保证不遵守有效用法规则时的任何结果。这被称为“未定义行为”,攻击者可以利用它访问非授权内存,或迫使驱动执行任意代码。
为禁止不安全用法,WebGPU 针对任意输入都定义了允许的行为范围。实现必须校验所有用户输入,只允许有效工作负载到达驱动。本规范规定了所有错误条件及其处理语义。例如,在 copyBufferToBuffer() 的 "source" 和 "destination"
同时指定同一缓冲区,且区间相交时,GPUCommandEncoder
会生成错误,且不会执行其它操作。
更多错误处理信息参见 § 22 错误与调试。
2.1.2. 基于 GPU 的未定义行为
WebGPU 着色器 由 GPU 内部的计算单元执行。在原生 API
中,某些着色器指令可能在 GPU 上导致未定义行为。为应对这一点,WebGPU 严格定义了着色器指令集及其行为。当为 createShaderModule()
提供着色器时,WebGPU 实现必须在进行任何平台特定着色器转换或变换之前进行校验。
2.1.3. 未初始化数据
一般来说,分配新内存可能暴露系统上其它应用残留的数据。为避免此问题,WebGPU 在概念上会将所有资源初始化为零,尽管若实现检测到开发者已手动初始化内容时可跳过此步骤。这包括着色器内变量和共享工作组内存。
清除工作组内存的具体机制依平台而异。若原生 API 未提供清除机制,WebGPU 实现会先在所有调用中清空,再同步,然后继续执行开发者代码。
GPULoadOp
"load"
改为 "clear")。
因此,无论实现是否有性能损耗,所有实现应当在开发者控制台发出警告。
2.1.4. 着色器中的越界访问
着色器可以直接访问物理资源(如 "uniform"
GPUBufferBinding),也可以通过纹理单元(为纹理坐标转换而设的固定功能硬件块)间接访问。WebGPU API 的校验只能保证所有着色器输入已提供且类型正确。如果未通过纹理单元访问,WebGPU API 无法保证数据访问不会越界。
为防止着色器访问非本应用 GPU 内存,WebGPU 实现可在驱动中启用“健壮缓冲区访问”模式,确保访问不会超出缓冲区界限。
或者,实现可在着色器代码中插入手动越界检查。此时,越界检查仅适用于数组索引,对结构体字段访问则无需手动检查,因为主机侧 minBindingSize
校验已覆盖。
若着色器尝试读取物理资源边界外的数据,实现可以:
-
返回资源边界内其他位置的值
-
返回值向量 "(0, 0, 0, X)",其中 X 可为任意值
-
部分丢弃绘制或调度调用
若着色器尝试写入物理资源边界外,实现可以:
-
写入资源边界内其他位置
-
丢弃写入操作
-
部分丢弃绘制或调度调用
2.1.5. 无效数据
从 CPU 向 GPU 上传 浮点数数据或在 GPU 上生成浮点数时,可能会出现不对应于有效数值的二进制表示(如无穷大或 NaN)。此时 GPU 行为取决于硬件对 IEEE-754 标准的实现精度。WebGPU 保证引入无效浮点数只会影响算术运算结果,不会有其他副作用。
2.1.6. 驱动漏洞
GPU 驱动程序和其他软件一样可能存在漏洞。攻击者可能利用驱动的错误行为访问非授权数据。为降低风险,WebGPU 工作组将与 GPU 厂商协作,将 WebGPU 一致性测试套件(CTS)集成到驱动测试流程中,类似 WebGL 的做法。WebGPU 实现应对已发现的部分漏洞有兼容性处理,并对无法绕过的已知漏洞驱动禁用 WebGPU。
2.1.7. 时序攻击
2.1.7.1. 内容时间线时序
WebGPU 不会向 JavaScript 暴露在 内容时间线上由 agent 在 agent cluster
中共享的新状态。内容时间线状态如 [[mapping]]
仅在显式 内容时间线任务(如普通
JavaScript)中变化。
2.1.7.2. 设备/队列时间线时序
可写存储缓冲区和其他跨调用通信机制可能用于在队列时间线上构造高精度定时器。
可选的 "timestamp-query"
特性也为 GPU 操作提供高精度计时。为缓解安全和隐私风险,定时查询的值被对齐到较低精度:参见 current queue timestamp。特别注意:
-
设备时间线通常在多个源共享的进程中运行,因此跨源隔离(如 COOP/COEP)无法隔离设备/队列时间线定时器。
-
队列时间线工作由设备时间线发起,可能在不能像 CPU 进程(如 Meltdown 缓解)那样隔离的 GPU 硬件上执行。
-
GPU 硬件通常不易受到 Spectre 类攻击,但 WebGPU 可能在软件中实现,软件实现可能运行在共享进程中,无法依赖隔离缓解。
2.1.8. Row hammer 攻击
Row hammer 是一类利用 DRAM 单元状态泄漏的攻击,可被用于 GPU。WebGPU 没有专门的防护措施,依赖于平台级解决方案,例如缩短内存刷新间隔。
2.1.9. 拒绝服务
WebGPU 应用可访问 GPU 内存和计算单元。WebGPU 实现可以限制应用可用的 GPU 内存,以保证其他应用的响应性。对于 GPU 处理时间,WebGPU 实现可以设置“看门狗”定时器,确保应用不会导致 GPU 无响应超过数秒。这些措施类似于 WebGL 所采用的策略。
2.1.10. 工作负载识别
WebGPU 提供对全局受限资源的访问,这些资源由同一台机器上不同程序(和网页)共享。应用可通过间接探测全局资源受限程度,进而推测其他网页正在进行的工作负载。这些问题与 Javascript 中的系统内存和 CPU 执行吞吐量类似。WebGPU 没有对此提供额外的缓解措施。
2.1.11. 内存资源
WebGPU 允许从机器全局内存堆(如 VRAM)进行可失败的分配。这使得应用可以通过尝试分配并观察分配失败情况,探测系统剩余可用内存(针对特定堆类型)。
GPU 内部一般有一个或多个(通常只有两个)所有运行应用共享的内存堆。当某个堆耗尽时,WebGPU 创建资源会失败。这是可观察到的,可能使恶意应用推测出其他应用使用了哪些堆,以及它们分配了多少。
2.1.12. 计算资源
如果一个站点与另一个站点同时使用 WebGPU,它可能会观察到处理某些工作的耗时增加。例如,持续向队列提交计算工作并跟踪完成时间,可能会发现其他任务也开始使用 GPU。
GPU 有多个可独立测试的部分,如算术单元、纹理采样单元、原子单元等。恶意应用可以检测某些单元的负载,并试图分析压力模式来猜测其他应用的工作负载。这与 Javascript 的 CPU 执行现实类似。
2.1.13. 能力滥用
恶意站点可能滥用 WebGPU 所暴露的能力,运行对用户或其体验无益、仅对站点有利的计算。例如隐蔽挖矿、密码破解或彩虹表计算。
无法针对这类 API 使用方式加以防范,因为浏览器无法区分有效负载和滥用负载。这是 Web 上所有通用计算能力(如 JavaScript、WebAssembly 或 WebGL)面临的普遍问题。WebGPU 只是让某些负载的实现更容易,或比 WebGL 更高效。
为缓解此类滥用,浏览器可对后台标签页的操作进行限速,可警告标签页资源占用过高,并可限制哪些上下文允许使用 WebGPU。
用户代理可基于启发式方法向用户发出高功耗警告,尤其在检测到潜在恶意使用时。如果实现此类警告,应将 WebGPU 使用纳入与 JavaScript、WebAssembly、WebGL 等相同的启发式中。
2.2. 隐私考量
WebGPU 的隐私考量与 WebGL 类似。GPU API 十分复杂,必须出于必要暴露设备能力的各个方面,以便开发者能够有效利用这些能力。一般的缓解方法是对潜在可识别信息进行归一化或分桶,并在可能的情况下强制行为一致。
用户代理不得暴露超过 32 种可区分配置或分桶。
2.2.1. 机器特有功能与限制
WebGPU 可以揭示底层 GPU 架构和设备结构的许多细节,包括可用的物理适配器、GPU 和 CPU 资源的多项限制(如最大纹理尺寸),以及可用的任何可选硬件专属能力。
用户代理没有义务暴露真实硬件限制,可以完全控制机器细节的暴露程度。减少指纹识别的一种策略是将所有目标平台归为少数几个分桶。总体来说,暴露硬件限制的隐私影响与 WebGL 相同。
默认限制值也被故意设置得足够高,以便大多数应用无需请求更高限制即可运行。所有 API 的使用都按请求限制进行校验,因此不会因意外而向用户暴露实际硬件能力。
2.2.2. 机器特有产物
和 WebGL 一样,可以观察到一些机器特有的光栅化/精度差异和性能差异。这涉及光栅化覆盖及模式、着色器阶段间 varyings 的插值精度、计算单元调度,以及更多执行相关特性。
通常,同一厂商的大多数或全部设备的光栅化和精度指纹是相同的。性能差异难以完全规避,但信号强度较低(如 JS 执行性能)。
对隐私要求高的应用和用户代理应采用软件实现以消除这类产物。
2.2.3. 机器特有性能
通过测量 GPU 上特定操作的性能也是区分用户的一个因素。即便计时精度较低,重复执行某一操作也能体现用户机器在特定负载下的快慢。这是常见的识别向量(WebGL 和 Javascript 皆有),但信号较低且难以完全规避。
WebGPU 计算管线让开发者可绕过固定功能硬件直接访问 GPU,这带来了独特设备指纹识别的额外风险。用户代理可通过将逻辑 GPU 调用与实际计算单元解耦来降低此风险。
2.2.4. 用户代理状态
本规范未为源定义任何额外用户代理状态。但预期用户代理会对 GPUShaderModule、
GPURenderPipeline、
GPUComputePipeline
等高开销编译结果进行缓存。这些缓存有助于提升 WebGPU 应用首次访问后的加载速度。
对规范而言,这些缓存与极快编译无异,但应用可以轻易测量 createComputePipelineAsync()
的耗时。这可能导致跨源信息泄露(如“用户是否访问过包含特定着色器的站点”),因此用户代理应遵循 存储分区最佳实践。
系统的 GPU 驱动也可能有自己的着色器和管线编译缓存。用户代理可在可能的情况下禁用该缓存,或为着色器添加分区数据,使驱动将其视为不同对象。
2.2.5. 驱动漏洞
除安全考量中提到的问题外,驱动漏洞还可能导致行为差异,成为区分用户的手段。此处可采用安全考量中提及的缓解措施,如与 GPU 厂商协作,在用户代理中实现已知问题的兼容处理。
2.2.6. 适配器标识符
WebGL 实践表明,开发者有合理需求识别其代码运行的 GPU,以便创建和维护健壮的 GPU 内容。例如识别有已知驱动漏洞的适配器,以便规避或避免在某些硬件上使用表现不佳的特性。
但暴露适配器标识符自然会增加指纹识别信息量,因此有必要限制适配器识别的精度。
可以采取多项缓解措施以平衡内容健壮性与隐私保护。首先,用户代理可通过主动识别和规避已知驱动问题,减少开发者负担,就像浏览器开始用 GPU 以来所做的一样。
默认暴露适配器标识符时应尽量宽泛,只要有用即可。例如,可仅标识适配器厂商及架构而非具体型号。有时也可报告实际适配器的合理代理的标识符。
在需要完整详细适配器信息(如提交 bug 报告)时,可请用户同意向页面披露更多硬件信息。
最后,若用户代理认为合适(如增强隐私模式下),可完全不报告适配器标识符。
3. 基础
3.1. 约定
3.1.1. 语法速记
本规范中使用了如下语法速记:
.(点)语法,常见于编程语言。-
短语“
Foo.Bar”表示“值(或接口)Foo的Bar成员”。如果Foo是 有序映射(ordered map)且Bar在Foo中未存在,则返回undefined。 ?.(可选链)语法,借鉴自 JavaScript。-
短语“
Foo?.Bar”表示:“如果Foo为null或undefined或Bar在Foo中未存在,则为undefined;否则为Foo.Bar”。例如,若
buffer是一个GPUBuffer,则buffer?.\[[device]].\[[adapter]]表示:“如果buffer为null或undefined,则为undefined;否则为buffer的\[[device]]内部槽的\[[adapter]]内部槽。” ??(空值合并)语法,借鉴自 JavaScript。-
短语“
x??y”表示:“如果x不为 null 或 undefined,则为x,否则为y。” - 槽支持属性(slot-backed attribute)
-
由同名内部槽支持的 WebIDL 属性。其可变性视规范而定。
3.1.2. WebGPU 对象
WebGPU 接口定义了WebGPU 对象的公共接口和状态。它可在其创建的内容时间线上使用,此时它是 JavaScript 暴露的 WebIDL 接口。
任何包含 GPUObjectBase 的接口都是 WebGPU 接口。
内部对象跟踪WebGPU 对象在设备时间线上的状态。所有对内部对象可变状态的读写都发生在单一有序的设备时间线步骤中。
在WebGPU 对象上可定义以下特殊属性类型:
- 不可变属性(immutable property)
-
在对象初始化时设定的只读槽,可从任意时间线访问。
注:由于该槽不可变,实现可在多个时间线中保有副本,按需分配。不可变属性这样定义是为避免在规范中描述多个副本。
- 内容时间线属性(content timeline property)
-
仅可从对象创建的内容时间线访问的属性。
- 设备时间线属性(device timeline property)
-
跟踪内部对象状态,仅可从对象创建的设备时间线访问。设备时间线属性可为可变的。
设备时间线属性命名为
[[带括号]],为内部槽。 - 队列时间线属性(queue timeline property)
-
跟踪内部对象状态,仅可从对象创建的队列时间线访问。队列时间线属性可为可变的。
队列时间线属性命名为
[[带括号]],为内部槽。
interface mixin GPUObjectBase {attribute USVString label ; };
GPUObjectBase
parent,接口 T,GPUObjectDescriptorBase
descriptor)(其中 T 继承自 GPUObjectBase),请在内容时间线上执行以下步骤:
-
令 device 为 parent.
[[device]]。 -
令 object 为 T 的新实例。
-
设置 object.
[[device]]为 device。 -
返回 object。
GPUObjectBase
具有如下不可变属性:
GPUObjectBase
具有如下内容时间线属性:
label,类型为 USVString-
开发者提供的标签,由实现自定义使用。可由浏览器、操作系统或其他工具用于帮助开发者识别底层内部对象。示例包括在
GPUError消息、控制台警告、浏览器开发者工具和平台调试工具中显示标签。注:实现应当利用标签提升错误消息的可读性,用于标识 WebGPU 对象。但这不必是标识对象的唯一方式:实现还应结合其他可用信息,尤其是在没有标签时。例如:
-
打印
GPUTexture视图时,显示其父对象的标签。 -
打印
GPURenderPassEncoder或GPUComputePassEncoder时,显示其父GPUCommandEncoder的标签。 -
打印
GPUCommandBuffer时,显示其源GPUCommandEncoder的标签。 -
打印
GPURenderBundle时,显示其源GPURenderBundleEncoder的标签。
注:label是GPUObjectBase的属性。两个GPUObjectBase“包装器”对象即使引用同一底层对象,其 label 状态也是完全独立的(如由getBindGroupLayout()返回时)。除非通过 JavaScript 设置,否则label属性不会变更。这意味着一个底层对象可关联多个标签。本规范未定义标签如何传递到 设备时间线。标签的使用完全由实现自定义:错误消息可显示最近设置的标签、所有已知标签,或完全不显示标签。
属性类型为
USVString,因为某些用户代理可能将其传递给底层原生 API 的调试工具。 -
GPUObjectBase
具有如下设备时间线属性:
[[valid]],类型为boolean,初始值为true-
若为
true,表示该内部对象可用。
[[device]])被垃圾回收。然而,这无法保证,因为某些实现可能需要强引用父对象。
因此,开发者应假定 WebGPU 接口在所有子对象被回收前可能不会被垃圾回收。这可能导致部分资源比预期保留更长时间。
如果需要可预测地释放分配的资源,应优先调用 destroy 方法(如 GPUDevice.destroy()
或 GPUBuffer.destroy()),而不是依赖垃圾回收。
3.1.3. 对象描述符
对象描述符用于保存创建对象所需的信息,通常通过 GPUDevice 的 create*
方法之一进行对象创建。
dictionary {GPUObjectDescriptorBase USVString label = ""; };
GPUObjectDescriptorBase
具有如下成员:
label,类型为 USVString,默认值为""-
GPUObjectBase.label的初始值。
3.2. 异步性
3.2.1. 无效的内部对象与传染性无效
WebGPU 中的对象创建操作不会返回 Promise,但其本质上是异步的。返回的对象引用的是在设备时间线上被操作的内部对象。多数在设备时间线上发生的错误不会通过异常或拒绝抛出,而是通过关联设备上生成的 GPUError 进行传递。
内部对象可以是有效或无效。无效对象不会在之后变为有效,但部分有效对象可以被使无效(invalidated)。
如果对象无法被创建,则其从创建开始即为无效。例如,对象描述符未能描述出有效对象,或者没有足够内存分配资源时会发生此情况。如果从另一个无效对象创建对象(例如对无效的 GPUTexture 调用
createView()),也会如此。这类情况称为传染性无效。
大多数类型的内部对象在创建后不会变为无效,但仍可能变得不可用,例如其所属设备丢失或destroyed,或对象处于特殊内部状态(如缓冲区状态“destroyed”)。
部分类型的内部对象在创建后可以变为无效;具体包括设备、适配器、GPUCommandBuffer,以及命令/通道/捆绑编码器。
GPUObjectBase
object,若满足以下设备时间线步骤的所有要求,则其可与 targetObject 一同使用(valid to use with):
-
object.
[[valid]]必须为true。 -
object.
[[device]].[[valid]]必须为true。 -
object.
[[device]]必须等于 targetObject.[[device]]。
3.2.2. Promise 顺序
WebGPU 中有若干操作会返回 promise。
WebGPU 不保证这些 promise 的 settle(resolve 或 reject)顺序,除非有如下例外:
-
对于某个
GPUQueueq,如果 p1 = q.onSubmittedWorkDone()先于 p2 = q.onSubmittedWorkDone()被调用,则 p1 必须早于 p2 settle。 -
对于某个
GPUQueueq 和同一GPUDevice上的GPUBufferb,如果 p1 = b.mapAsync()先于 p2 = q.onSubmittedWorkDone()被调用,则 p1 必须早于 p2 settle。
应用不得依赖于其它 promise 的 settle 顺序。
3.3. 坐标系统
渲染操作使用如下坐标系统:
-
归一化设备坐标(NDC)有三维:
-
-1.0 ≤ x ≤ 1.0
-
-1.0 ≤ y ≤ 1.0
-
0.0 ≤ z ≤ 1.0
-
左下角为 (-1.0, -1.0, z)。
归一化设备坐标。 注:
z = 0还是z = 1作为近平面由应用决定。上图以z = 0为近平面,但实际行为由着色器使用的投影矩阵、depthClearValue和depthCompare函数共同决定。 -
-
裁剪空间坐标有四维:(x, y, z, w)
-
帧缓冲坐标用于寻址帧缓冲内的像素。
-
为二维坐标。
-
每个像素在 x、y 方向上长度为 1。
-
左上角为 (0.0, 0.0)。
-
x 向右递增。
-
y 向下递增。
-
参见 § 17 渲染通道 和 § 23.2.5 光栅化。
帧缓冲坐标。 -
-
视口坐标结合了 x、y 方向的帧缓冲坐标与 z 方向的深度。
-
通常 0.0 ≤ z ≤ 1.0,但可通过
[[viewport]].minDepth和maxDepth,以及setViewport()修改。
-
-
片元坐标与视口坐标一致。
-
纹理坐标,在 2D 中有时称为“UV 坐标”,用于采样纹理,其分量数量与
texture dimension匹配。-
0 ≤ u ≤ 1.0
-
0 ≤ v ≤ 1.0
-
0 ≤ w ≤ 1.0
-
(0.0, 0.0, 0.0) 位于纹理存储顺序的首个 texel。
-
(1.0, 1.0, 1.0) 位于纹理存储顺序的最后一个 texel。
二维纹理坐标。 -
-
窗口坐标,或称显示坐标,与帧缓冲坐标一致,用于与外部显示或类似接口交互时。
注:WebGPU 的坐标系统与 DirectX 图形管线中的坐标系统一致。
3.4. 编程模型
3.4.1. 时间线
WebGPU 的行为以“时间线”为单位进行描述。每个操作(以算法定义)都发生在某个时间线上。时间线明确了操作的顺序,以及哪些状态可被哪些操作访问。
注: 这种“时间线”模型反映了浏览器引擎多进程模型(如“内容进程”和“GPU 进程”)的约束,也体现了许多实现中 GPU 作为独立执行单元的现实。实现 WebGPU 并不要求时间线并行执行,因此不要求多进程,甚至不要求多线程。(但如 获取上下文图像内容副本 这类需同步阻塞其它时间线完成的情况,仍需支持并发。)
- 内容时间线
-
与 Web 脚本的执行相关。包括本规范描述的所有方法调用。
要从
GPUDevicedevice的操作向内容时间线派发步骤,可通过 为 GPUDevice 排队全局任务。 - 设备时间线
-
与用户代理发起的 GPU 设备操作相关。包括适配器、设备、GPU 资源与状态对象的创建,这些操作从用户代理控制 GPU 的部分看通常是同步的,但可在独立的操作系统进程中运行。
- 队列时间线
-
与 GPU 计算单元上操作的执行相关。包括实际在 GPU 上运行的绘制、拷贝和计算任务。
- 时间线无关
-
可以与上述任意时间线关联。
如仅操作不可变属性或调用步骤传入的参数,则可派发到任意时间线。
- 不可变值示例术语定义
-
可用于任意时间线。
- 内容时间线示例术语定义
-
仅可用于内容时间线。
- 设备时间线示例术语定义
-
仅可用于设备时间线。
- 队列时间线示例术语定义
-
仅可用于队列时间线。
本规范中,当返回值依赖于非内容时间线上发生的工作时,采用异步操作。API 以 promise 或事件的形式表现异步操作。
GPUComputePassEncoder.dispatchWorkgroups()
示例:
-
用户在 内容时间线 上通过
GPUComputePassEncoder的方法编码dispatchWorkgroups命令。 -
用户调用
GPUQueue.submit(),将GPUCommandBuffer提交给用户代理,用户代理在 设备时间线 上调用操作系统驱动进行底层提交。 -
GPU 调度器在 队列时间线 上将提交分派到实际计算单元执行。
GPUDevice.createBuffer()
示例:
-
用户填写
GPUBufferDescriptor,并用其创建GPUBuffer,在 内容时间线 上发生。 -
用户代理在 设备时间线 上创建底层缓冲区。
3.4.2. 内存模型
本节为非规范性内容。
一旦应用初始化过程中获取到 GPUDevice,我们可以将
WebGPU 平台描述为包含以下各层:
-
实现本规范的用户代理。
-
为该设备提供底层原生 API 驱动的操作系统。
-
实际的 CPU 和 GPU 硬件。
WebGPU 平台的每一层可能有不同类型的内存,用户代理在实现规范时需要加以考虑:
-
脚本拥有的内存,如脚本创建的
ArrayBuffer,通常无法被 GPU 驱动直接访问。 -
用户代理可能有不同进程分别负责内容运行和与 GPU 驱动的通信。在这种情况下,会使用进程间共享内存来传递数据。
-
独立显卡有自己的高带宽内存,而集成显卡通常与系统共享内存。
大多数物理资源分配在适合 GPU 计算或渲染的内存类型中。当用户需要向 GPU 提供新数据时,数据可能首先需要跨越进程边界,抵达与 GPU 驱动通信的用户代理部分。随后可能需要使数据对驱动可见,有时这需要拷贝到驱动分配的中转(staging)内存。最后,数据还可能需要传输到独立 GPU 内存中,并在内部转换为最适合 GPU 运算的布局。
所有这些转换都由用户代理的 WebGPU 实现负责完成。
注:上述示例描述了最坏情况,实际实现中可能无需跨越进程边界,或者能直接向用户暴露由驱动管理的内存(例如通过
ArrayBuffer),从而避免数据拷贝。
3.4.3. 资源用法
- 输入(input)
-
为 draw 或 dispatch 调用提供输入数据的缓冲区。会保留内容。由缓冲区
INDEX、VERTEX或INDIRECT允许。 - 常量(constant)
-
从着色器视角为常量的资源绑定。会保留内容。由缓冲区
UNIFORM或纹理TEXTURE_BINDING允许。 - 存储(storage)
-
读/写存储资源绑定。由缓冲区
STORAGE或纹理STORAGE_BINDING允许。 - 存储只读(storage-read)
-
只读存储资源绑定。会保留内容。由缓冲区
STORAGE或纹理STORAGE_BINDING允许。 - 附件(attachment)
-
在渲染通道中作为读/写输出附件或仅写解决目标的纹理。由纹理
RENDER_ATTACHMENT允许。 - 附件只读(attachment-read)
-
在渲染通道中作为只读附件的纹理。会保留内容。由纹理
RENDER_ATTACHMENT允许。
子资源(subresource)指整个缓冲区或纹理子资源。
-
U 中每个用法都是 存储。
即使可写,也允许有多个此类用法。这称为存储用法例外(usage scope storage exception)。
-
U 中每个用法都是 附件。
即使可写,也允许有多个此类用法。这称为附件用法例外(usage scope attachment exception)。
强制要求用法仅可组合为兼容用法列表,使得 API 能够限制内存操作中的数据竞争出现时机。该属性使基于 WebGPU 的应用更容易无修改地在不同平台上运行。
-
作为深度/模板附件,所有方面都标记为只读(根据需要使用
depthReadOnly和/或stencilReadOnly)。 -
作为 draw 调用的纹理绑定。
-
一个缓冲区或纹理可作为存储绑定到渲染通道的两个不同 draw 调用。
-
单个缓冲区的不相交区间可分别作为存储绑定到两个不同绑定点。
重叠区间不得在单一 dispatch/draw 调用中绑定;这由“编码器绑定组别名可写资源”检查。
但同一切片不得作为两个不同附件重复绑定;这由 beginRenderPass()
检查。
3.4.4. 同步机制
用法范围(usage scope)是一个从有序映射,其键为子资源,值为 列表<内部用法>。每个用法范围覆盖一组可能并发执行的操作,因此在该范围内对子资源的使用只能是兼容用法列表。
用法范围在编码期间被构建和校验:
用法范围如下:
-
在计算通道中,每个 dispatch 命令(
dispatchWorkgroups()或dispatchWorkgroupsIndirect())即为一个用法范围。若某子资源在当前 dispatch 调用中可能被访问,则视为在该用法范围内被使用,包括:
-
当前
GPUComputePipeline的[[layout]]所用绑定组(bind group)槽引用的全部子资源 -
dispatch 调用直接使用的缓冲区(如间接缓冲区)
注: 诸如 setBindGroup() 等状态设定命令本身不会直接将绑定资源计入用法范围,它们只改变 dispatch 命令检查的状态。
-
-
一次渲染通道(render pass)即为一个用法范围。
若某子资源在任何命令中被引用(包括状态设定命令,与计算通道不同),则视为在该用法范围内被使用,包括:
-
通过
setVertexBuffer()设置的缓冲区 -
通过
setIndexBuffer()设置的缓冲区 -
通过 setBindGroup() 设置的绑定组引用的所有子资源
-
draw 调用直接使用的缓冲区(如间接缓冲区)
-
注:拷贝命令为独立操作,不使用用法范围进行校验,其自身实现了防止自竞争的校验。
-
在渲染通道中,任何 setBindGroup() 调用所用的子资源,无论当前绑定的管线着色器/布局是否真的依赖这些绑定,或该绑定组是否被后续 set 覆盖。
-
任何
setVertexBuffer()调用所用缓冲区,无论是否有 draw 调用依赖该缓冲区,或该缓冲区是否被后续 set 覆盖。 -
任何
setIndexBuffer()调用所用缓冲区,无论是否有 draw 调用依赖该缓冲区,或该缓冲区是否被后续 set 覆盖。 -
作为颜色附件、解决附件或深度/模板附件用于
GPURenderPassDescriptor的纹理子资源,被beginRenderPass()使用,无论着色器是否真的依赖这些附件。 -
在绑定组条目中具有可见性 0,或仅对计算阶段可见但被用于渲染通道的资源(反之亦然)。
3.5. 核心内部对象
3.5.1. 适配器(Adapters)
适配器(adapter)标识系统上的 WebGPU 实现:既包括底层平台上的计算/渲染功能实例,也包括浏览器在该功能之上实现 WebGPU 的实例。
适配器通过 GPUAdapter
暴露。
适配器并不唯一代表底层实现:多次调用 requestAdapter()
每次都会返回不同的适配器对象。
每个 适配器对象只能用于创建一个 设备(device):一旦成功调用 requestDevice(),该适配器的
[[state]]
变为 "consumed"。此外,适配器对象可能在任何时刻过期(expire)。
注:
这样保证应用在创建设备时能使用最新的系统状态来选择适配器。也让多种场景(如首次初始化、因适配器移除重初始化、因 GPUDevice.destroy()
测试重初始化等)行为保持一致,提高健壮性。
若适配器以显著性能换取更广兼容性、更可预测行为或更好的隐私,则可视为回退适配器(fallback adapter)。不是每个系统都必须提供回退适配器。
[[features]],类型为 有序集合<GPUFeatureName>,只读-
可用于在此适配器上创建设备的特性。
[[limits]],类型为支持的限制,只读[[fallback]],类型为boolean,只读-
为
true时,表示该适配器是回退适配器。 [[xrCompatible]],类型为 boolean-
为
true时,表示该适配器请求了与 WebXR 会话 兼容。
[[state]],初始值为"valid"-
"valid"-
适配器可用于创建设备。
"consumed"-
适配器已被用于创建设备,不能再次使用。
"expired"-
适配器因其他原因已过期。
3.5.2. 设备(Devices)
设备(device)是适配器的逻辑实例,通过它可以创建内部对象。
一个设备独占其上创建的所有内部对象:当该设备变为无效(丢失或 销毁时),它本身和所有直接(如
createTexture())或间接(如
createView())创建的对象都会隐式变为不可用。
[[adapter]],类型为 适配器,只读-
创建该设备的适配器。
[[features]],类型为 有序集合<GPUFeatureName>,只读[[limits]],类型为支持的限制,只读
GPUDeviceDescriptor
descriptor 创建新设备,请执行以下设备时间线步骤:
-
令 features 为 descriptor.
requiredFeatures中值的有序集合。 -
如果 features 包含
"texture-formats-tier2":-
追加
"texture-formats-tier1"到 features。
-
-
如果 features 包含
"texture-formats-tier1":-
追加
"rg11b10ufloat-renderable"到 features。
-
-
追加
"core-features-and-limits"到 features。 -
令 limits 为所有值均为默认值的支持的限制对象。
-
对于 descriptor.
requiredLimits中每个 (key, value):-
如果 value 不为
undefined且 value 优于 limits[key]:-
设 limits[key] = value。
-
-
-
令 device 为新设备对象。
-
设 device.
[[adapter]]= adapter。 -
设 device.
[[features]]= features。 -
设 device.
[[limits]]= limits。 -
返回 device。
每当用户代理需要撤销设备访问权限时,会在该设备的设备时间线上调用 丢失设备(device, "unknown"),该操作可能优先于当前队列中的其他操作。
如果某操作失败且副作用可能导致设备上的对象状态可见变化或内部实现/驱动状态损坏,应当丢失该设备以防止这些变化被观察到。
注:
非应用主动发起的设备丢失(通过 destroy())时,用户代理应无条件向开发者发出警告,即使
lost
promise 已被处理。此类场景应极其罕见,并且该信号对开发者至关重要,因为大多数 WebGPU API 会尽量表现为“一切正常”以避免中断运行时流程:不会抛出校验错误,大多数 promise 正常 resolve
等。
-
在 device.
[[content device]]的内容时间线上执行: -
完成所有等待 device 变为丢失的未完成步骤。
注:丢失的设备不会再生成错误。参见 § 22 错误与调试。
则在 timeline 上执行 steps。
3.6. 可选功能
WebGPU 适配器和设备具备功能,这些功能描述了WebGPU在不同实现之间的差异, 通常是由于硬件或系统软件的限制。 一项功能可以是特性或限制。
用户代理不得透露超过32个可区分的配置或分组。
适配器的功能必须符合§ 4.2.1 适配器功能保证。
仅支持的功能可以在requestDevice()中请求;
请求不支持的功能会导致失败。
设备的功能在"一个新的设备"中确定,
通过从适配器的默认值(无特性和默认的支持的限制)开始,
并根据在requestDevice()中请求的功能添加功能。
这些功能无论适配器的功能如何均会被强制执行。
有关隐私方面的考虑,请参阅§ 2.2.1 机器特定的功能和限制。
3.6.1. 特性
特性是一组可选的 WebGPU 功能,并非所有实现都支持这些功能,通常是由于硬件或系统软件的限制所致。
所有特性都是可选的,但适配器会对其可用性做出一定保证 (参见§ 4.2.1 适配器功能保证)。
设备仅支持在创建时确定的那组特性(参见§ 3.6 可选功能)。 API 调用将根据这些特性(而非适配器的特性)进行校验:
-
以新方式使用已有的 API 接口通常会导致校验错误。
-
有几种类型的可选 API 接口:
-
使用新方法或枚举值时总是抛出
TypeError异常。 -
使用带有(正确类型)非默认值的新字典成员通常会导致校验错误。
-
使用新的 WGSL
enable指令时,总是会在createShaderModule()的过程中产生校验错误。
-
每个特性所启用的功能描述可参见特性索引。
注意: 启用特性未必是理想选择,可能会影响性能。 因此,为了提升不同设备和实现间的可移植性,应用程序通常只应请求实际需要的特性。
3.6.2. 限制
每个限制都是对设备上 WebGPU 使用的数值限制。
注意: 设置“更好”的限制未必是理想选择,因为这样可能会对性能产生影响。 因此,为了提升不同设备和实现之间的可移植性,应用程序通常只有在确实需要时才请求比默认值更好的限制。
每个限制都有一个默认值。
适配器始终保证支持默认值或更好的 (参见§ 4.2.1 适配器功能保证)。
设备仅支持在创建时确定的那组限制(参见§ 3.6 可选功能)。 API 调用根据这些限制进行校验(而非适配器的限制), 不允许“更好”或更差。
对于任何给定的限制,一些值是更好的。 更好的限制值始终放宽校验,从而使更多程序变得有效。 对于每个限制类别,“更好”的定义如下。
不同的限制具有不同的限制类别:
支持的限制 对象具有 WebGPU 定义的每个限制的值:
| 限制名称 | 类型 | 限制类别 | 默认值 |
|---|---|---|---|
maxTextureDimension1D
| GPUSize32
| 最大值 | 8192 |
创建dimension
"1d"的纹理时,
size.width
的最大允许值。
| |||
maxTextureDimension2D
| GPUSize32
| 最大值 | 8192 |
创建dimension
"2d"的纹理时,
size.width
和 size.height
的最大允许值。
| |||
maxTextureDimension3D
| GPUSize32
| 最大值 | 2048 |
创建dimension
"3d"的纹理时,
size.width、
size.height
和 size.depthOrArrayLayers 的最大允许值。
| |||
maxTextureArrayLayers
| GPUSize32
| 最大值 | 256 |
创建dimension
"2d"的纹理时,
size.depthOrArrayLayers
的最大允许值。
| |||
maxBindGroups
| GPUSize32
| 最大值 | 4 |
创建GPUPipelineLayout时,
bindGroupLayouts
中允许的GPUBindGroupLayouts的最大数量。
| |||
maxBindGroupsPlusVertexBuffers
| GPUSize32
| 最大值 | 24 |
同时使用的绑定组和顶点缓冲区槽位的最大数量,包括所有低于最大索引的空槽位。
在createRenderPipeline()
和绘制调用中验证。
| |||
maxBindingsPerBindGroup
| GPUSize32
| 最大值 | 1000 |
创建GPUBindGroupLayout时可用的绑定索引数量。
注意: 此限制具有规范性,但属于人为设定。
按默认绑定槽位限制,一个绑定组实际上无法使用1000个绑定,
但这允许 | |||
maxDynamicUniformBuffersPerPipelineLayout
| GPUSize32
| 最大值 | 8 |
在一个GPUPipelineLayout中,
所有为动态偏移的uniform buffer的GPUBindGroupLayoutEntry条目的最大数量。
详见绑定槽位限制说明。
| |||
maxDynamicStorageBuffersPerPipelineLayout
| GPUSize32
| 最大值 | 4 |
在一个GPUPipelineLayout中,
所有为动态偏移的storage buffer的GPUBindGroupLayoutEntry条目的最大数量。
详见绑定槽位限制说明。
| |||
maxSampledTexturesPerShaderStage
| GPUSize32
| 最大值 | 16 |
对于每个GPUShaderStage
stage,在一个GPUPipelineLayout中,
所有采样纹理的GPUBindGroupLayoutEntry条目的最大数量。
详见绑定槽位限制说明。
| |||
maxSamplersPerShaderStage
| GPUSize32
| 最大值 | 16 |
对于每个GPUShaderStage
stage,在一个GPUPipelineLayout中,
所有采样器的GPUBindGroupLayoutEntry条目的最大数量。
详见绑定槽位限制说明。
| |||
maxStorageBuffersPerShaderStage
| GPUSize32
| 最大值 | 8 |
对于每个GPUShaderStage
stage,在一个GPUPipelineLayout中,
所有存储缓冲区的GPUBindGroupLayoutEntry条目的最大数量。
详见绑定槽位限制说明。
| |||
maxStorageTexturesPerShaderStage
| GPUSize32
| 最大值 | 4 |
对于每个可能的GPUShaderStage
stage,
在一个GPUPipelineLayout中,
所有存储纹理类型GPUBindGroupLayoutEntry的最大数量。
详见绑定槽位限制说明。
|
|||
maxUniformBuffersPerShaderStage
|
GPUSize32
|
最大值 | 12 |
对于每个可能的GPUShaderStage
stage,
在一个GPUPipelineLayout中,
所有uniform buffer类型GPUBindGroupLayoutEntry的最大数量。
详见绑定槽位限制说明。
|
|||
maxUniformBufferBindingSize
|
GPUSize64
|
最大值 | 65536 字节 |
绑定类型为
GPUBindGroupLayoutEntry
,且entry.buffer?.type
为 "uniform"
时,
GPUBufferBinding.size
的最大值。
|
|||
maxStorageBufferBindingSize
|
GPUSize64
|
最大值 | 134217728 字节(128 MiB) |
绑定类型为
GPUBindGroupLayoutEntry
,且entry.buffer?.type
为 "storage"
或 "read-only-storage"
时,
GPUBufferBinding.size
的最大值。
|
|||
minUniformBufferOffsetAlignment
|
GPUSize32
|
对齐 | 256 字节 |
绑定类型为
GPUBindGroupLayoutEntry
,且entry.buffer?.type
为 "uniform"
时,
GPUBufferBinding.offset
以及 setBindGroup() 传入的动态偏移量所需的对齐要求。
|
|||
minStorageBufferOffsetAlignment
|
GPUSize32
|
对齐 | 256 字节 |
绑定类型为
GPUBindGroupLayoutEntry
,且entry.buffer?.type
为 "storage"
或 "read-only-storage"
时,
GPUBufferBinding.offset
以及 setBindGroup() 传入的动态偏移量所需的对齐要求。
|
|||
maxVertexBuffers
|
GPUSize32 |
最大值 | 8 |
创建GPURenderPipeline时,允许的buffers的最大数量。
|
|||
maxBufferSize |
GPUSize64 |
最大值 | 268435456 字节(256 MiB) |
创建GPUBuffer时,size的最大数值。
|
|||
maxVertexAttributes |
GPUSize32 |
最大值 | 16 |
创建GPURenderPipeline时,所有attributes在buffers中的总和的最大数量。
|
|||
maxVertexBufferArrayStride
|
GPUSize32 |
最大值 | 2048 字节 |
创建GPURenderPipeline时,arrayStride的最大允许值。
|
|||
maxInterStageShaderVariables
|
GPUSize32 |
最大值 | 16 |
| 阶段间通信(如顶点输出、片元输入)可用的输入或输出变量的最大数量。 | |||
maxColorAttachments |
GPUSize32 |
最大值 | 8 |
在
GPURenderPipelineDescriptor.fragment.targets、
GPURenderPassDescriptor.colorAttachments
和 GPURenderPassLayout.colorFormats
中允许的最大颜色附件数量。
|
|||
maxColorAttachmentBytesPerSample
|
GPUSize32
|
最大值 | 32 |
| 渲染管线输出数据中,跨所有颜色附件存储一个采样(像素或子像素)所需的最大字节数。 | |||
maxComputeWorkgroupStorageSize
|
GPUSize32
|
最大值 | 16384 字节 |
一个计算阶段GPUShaderModule入口点可用的workgroup存储的最大字节数。
|
|||
maxComputeInvocationsPerWorkgroup
|
GPUSize32
|
最大值 | 256 |
一个计算阶段GPUShaderModule入口点的workgroup_size各维度乘积的最大值。
|
|||
maxComputeWorkgroupSizeX
|
GPUSize32
|
最大值 | 256 |
一个计算阶段GPUShaderModule入口点的workgroup_size
X 维度的最大值。
|
|||
maxComputeWorkgroupSizeY
|
GPUSize32
|
最大值 | 256 |
一个计算阶段GPUShaderModule入口点的workgroup_size
Y 维度的最大值。
|
|||
maxComputeWorkgroupSizeZ
|
GPUSize32
|
最大值 | 64 |
一个计算阶段GPUShaderModule入口点的workgroup_size
Z 维度的最大值。
|
|||
maxComputeWorkgroupsPerDimension
|
GPUSize32
|
最大值 | 65535 |
dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ)的参数的最大值。
|
|||
3.6.2.1.
GPUSupportedLimits
GPUSupportedLimits
用于暴露适配器或设备的支持的限制。
参见 GPUAdapter.limits
和 GPUDevice.limits。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUSupportedLimits {readonly attribute unsigned long ;maxTextureDimension1D readonly attribute unsigned long ;maxTextureDimension2D readonly attribute unsigned long ;maxTextureDimension3D readonly attribute unsigned long ;maxTextureArrayLayers readonly attribute unsigned long ;maxBindGroups readonly attribute unsigned long ;maxBindGroupsPlusVertexBuffers readonly attribute unsigned long ;maxBindingsPerBindGroup readonly attribute unsigned long ;maxDynamicUniformBuffersPerPipelineLayout readonly attribute unsigned long ;maxDynamicStorageBuffersPerPipelineLayout readonly attribute unsigned long ;maxSampledTexturesPerShaderStage readonly attribute unsigned long ;maxSamplersPerShaderStage readonly attribute unsigned long ;maxStorageBuffersPerShaderStage readonly attribute unsigned long ;maxStorageTexturesPerShaderStage readonly attribute unsigned long ;maxUniformBuffersPerShaderStage readonly attribute unsigned long long ;maxUniformBufferBindingSize readonly attribute unsigned long long ;maxStorageBufferBindingSize readonly attribute unsigned long ;minUniformBufferOffsetAlignment readonly attribute unsigned long ;minStorageBufferOffsetAlignment readonly attribute unsigned long ;maxVertexBuffers readonly attribute unsigned long long ;maxBufferSize readonly attribute unsigned long ;maxVertexAttributes readonly attribute unsigned long ;maxVertexBufferArrayStride readonly attribute unsigned long ;maxInterStageShaderVariables readonly attribute unsigned long ;maxColorAttachments readonly attribute unsigned long ;maxColorAttachmentBytesPerSample readonly attribute unsigned long ;maxComputeWorkgroupStorageSize readonly attribute unsigned long ;maxComputeInvocationsPerWorkgroup readonly attribute unsigned long ;maxComputeWorkgroupSizeX readonly attribute unsigned long ;maxComputeWorkgroupSizeY readonly attribute unsigned long ;maxComputeWorkgroupSizeZ readonly attribute unsigned long ; };maxComputeWorkgroupsPerDimension
3.6.2.2.
GPUSupportedFeatures
GPUSupportedFeatures
是一个 类似集合(setlike) 接口。它的
集合条目
是适配器或设备支持的 GPUFeatureName
值。
它只能包含 GPUFeatureName
枚举中的字符串。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUSupportedFeatures {readonly setlike <DOMString >; };
GPUSupportedFeatures
的 集合条目
类型为 DOMString,
这样可以让用户代理优雅地处理后续规范修订中新增但用户代理尚未识别的有效 GPUFeatureName。
如果 集合条目 的类型是
GPUFeatureName,如下代码将抛出
TypeError,
而不是返回 false:
3.6.2.3.
WGSLLanguageFeatures
WGSLLanguageFeatures
是
navigator.gpu.
的
类似集合(setlike) 接口。
它的 集合条目
是该实现支持的 WGSL 语言扩展 的字符串名称(不论适配器或设备)。
wgslLanguageFeatures
[Exposed =(Window ,Worker ),SecureContext ]interface WGSLLanguageFeatures {readonly setlike <DOMString >; };
3.6.2.4.
GPUAdapterInfo
GPUAdapterInfo
用于暴露关于适配器的各种标识信息。
GPUAdapterInfo
的成员不保证有任何特定值;如果没有提供值,该属性将返回空字符串
""。是否揭示这些值由用户代理自行决定,并且某些设备上可能所有值都为空。因此,应用必须能够处理任何可能的
GPUAdapterInfo
值,包括这些值缺失的情况。
适配器的 GPUAdapterInfo
可通过 GPUAdapter.info
和 GPUDevice.adapterInfo
获取。
这些信息是不可变的:对于某个适配器,每次访问同一个 GPUAdapterInfo
属性都会返回相同的值。
注意:
虽然 GPUAdapterInfo
属性一旦访问就不可变,
但实现可以在首次访问前延后决定每个属性的内容。
注意:
即便其他 GPUAdapter
实例代表同一物理适配器,
它们在 GPUAdapterInfo
中揭示的值也可能不同。
但除非有特殊事件提升了页面可访问的标识信息(本规范未定义此类事件),否则它们应当揭示相同的值。
关于隐私考虑,请参见 § 2.2.6 适配器标识符。
[Exposed =(Window ,Worker ),SecureContext ]interface GPUAdapterInfo {readonly attribute DOMString vendor ;readonly attribute DOMString architecture ;readonly attribute DOMString device ;readonly attribute DOMString description ;readonly attribute unsigned long subgroupMinSize ;readonly attribute unsigned long subgroupMaxSize ;readonly attribute boolean isFallbackAdapter ; };
GPUAdapterInfo
拥有如下属性:
-
vendor, 类型为 DOMString,只读 -
适配器的厂商名称(如有)。否则为空字符串。
-
architecture, 类型为 DOMString,只读 -
适配器所属 GPU 家族或类别的名称(如有)。否则为空字符串。
-
device, 类型为 DOMString,只读 -
适配器的厂商自定义标识符(如有)。否则为空字符串。
注意: 这是代表适配器类型的值。例如,可能是 PCI 设备ID。它不会像序列号一样唯一标识某块硬件。
-
description, 类型为 DOMString,只读 -
驱动报告的关于适配器的人类可读字符串描述(如有)。否则为空字符串。
注意:
description没有采用任何格式化,不建议尝试解析此值。根据GPUAdapterInfo改变行为的应用(如为已知驱动问题应用修正),应尽量依赖其他字段。 -
subgroupMinSize, 类型为 unsigned long,只读 -
如果支持
"subgroups"特性,则为适配器支持的最小 子组大小。 -
subgroupMaxSize, 类型为 unsigned long,只读 -
如果支持
"subgroups"特性,则为适配器支持的最大 子组大小。 -
isFallbackAdapter, 类型为 boolean,只读 -
适配器是否为回退适配器。
-
令 adapterInfo 为新的
GPUAdapterInfo。 -
如果已知厂商,则将 adapterInfo.
vendor设为 adapter 的厂商名,并格式化为规范化标识符字符串。为保护隐私,用户代理也可以将 adapterInfo.vendor设为空字符串,或一个合理近似的厂商名(同样为规范化标识符字符串)。 -
如果已知架构,则将 adapterInfo.
architecture设为代表 adapter 所属 GPU 家族或类别的规范化标识符字符串。为保护隐私,用户代理也可以设为空字符串,或合理近似的架构名(同样为规范化标识符字符串)。 -
如果已知设备,则将 adapterInfo.
device设为 adapter 的厂商自定义标识符,并格式化为规范化标识符字符串。为保护隐私,用户代理也可以设为空字符串,或合理近似的标识符(同样为规范化标识符字符串)。 -
如果已知描述,则将 adapterInfo.
description设为驱动报告的 adapter 描述。为保护隐私,用户代理也可以设为空字符串,或合理近似的描述。 -
如果支持
"subgroups"特性,则将subgroupMinSize设为支持的最小子组大小;否则设为 4。注意: 为保护隐私,用户代理可以选择不支持某些特性,或为属性提供不会区分不同设备但依然可用的值(如对所有设备使用默认值 4)。
-
如果支持
"subgroups"特性,则将subgroupMaxSize设为支持的最大子组大小;否则设为 128。注意: 为保护隐私,用户代理可以选择不支持某些特性,或为属性提供不会区分不同设备但依然可用的值(如对所有设备使用默认值 128)。
-
将 adapterInfo.
isFallbackAdapter设为 adapter.[[fallback]]。 -
返回 adapterInfo。
[a-z0-9]+(-[a-z0-9]+)*
3.7. 扩展文档
“扩展文档”是描述新功能的附加文档,这些功能是非规范性的,不属于 WebGPU/WGSL 规范的一部分。
它们描述了在这些规范基础上构建的功能,通常包含一个或多个新的 API 特性标志和/或
WGSL enable 指令,或与其他草案 Web 规范的交互。
WebGPU 实现不得暴露扩展功能;这样做属于规范违规。 新功能只有在被集成到 WebGPU 规范(本文档)和/或 WGSL 规范后,才成为 WebGPU 标准的一部分。
3.8. 源限制(Origin Restrictions)
WebGPU 允许访问存储在图片、视频和画布中的图像数据。 出于安全原因,对跨域媒体的使用施加了限制,因为着色器可以被用来间接推测已上传到 GPU 的纹理内容。
WebGPU 不允许上传 不是 origin-clean 的图片源。
这也意味着,使用 WebGPU 渲染的 canvas 的 origin-clean 标志永远不会被置为 false。
关于为图片和视频元素发起 CORS 请求的更多信息,请参考:
3.9. 任务源(Task Sources)
3.9.1. WebGPU 任务源
WebGPU 定义了一个新的 任务源,称为 WebGPU 任务源。
它用于 uncapturederror
事件和
GPUDevice.lost。
GPUDevice
device 排队一个全局任务(queue a global task),并在 内容时序 上执行一系列步骤
steps:
-
在 WebGPU 任务源 上,为用于创建 device 的全局对象,按 steps 排队一个全局任务。
3.9.2. 自动过期任务源
WebGPU 定义了一个新的 任务源,称为 自动过期任务源。 它用于自动、定时地销毁某些对象:
来自 自动过期任务源 的任务应当以高优先级处理;尤其是排入队列后,应当在用户自定义(JavaScript)任务之前执行。
实现说明: 以高优先级处理过期“任务”也可以通过在事件循环处理模型的某个固定点插入额外步骤来实现,而不一定非要运行实际的任务。
3.10. 色彩空间与编码
WebGPU 不提供色彩管理。WebGPU 内的所有值(如纹理元素)都是原始数值,不是经过色彩管理的色值。
WebGPU 确实与色彩管理的输出(通过 GPUCanvasConfiguration)和输入(通过
copyExternalImageToTexture()
及 importExternalTexture())对接。因此,必须在
WebGPU 数值和外部色值之间进行色彩转换。每个接口点都会本地定义一种编码(色彩空间、传递函数和 alpha 预乘),用于解释 WebGPU 的数值。
WebGPU 允许 PredefinedColorSpace
枚举中的所有色彩空间。注意,每个色彩空间都定义了扩展范围(详见 CSS 相关定义),可以表示其空间外的颜色值(包括色度和明度)。
超出色域的预乘
RGBA 值指 R/G/B 其中任意一个通道的值大于 alpha 通道的值。例如,预乘 sRGB RGBA 值 [1.0, 0, 0, 0.5] 表示原始(未预乘)颜色 [2, 0, 0] 且
alpha 为 50%,在 CSS 中可写作 rgb(srgb 2 0 0 / 50%)。和所有 sRGB 色域外的颜色一样,这在扩展色彩空间中是有定义的点(alpha 为 0
时除外,此时没有颜色)。但若此类值输出到可见画布,结果未定义(见 GPUCanvasAlphaMode
"premultiplied")。
3.10.1. 色彩空间转换
颜色在空间间转换时,需根据上述定义将其在一个空间中的表示转换为另一个空间中的表示。
如果源值少于4个 RGBA 通道,则缺失的绿/蓝/alpha 通道分别设为0, 0, 1,然后再做色彩空间/编码和 alpha 预乘转换。转换后,如果目标需要的通道数少于4,则忽略多余通道。
注意: 灰度图像通常在其色彩空间下表现为 RGB 值 (V, V, V) 或 RGBA
值 (V, V, V, A)。
颜色在转换时不会被有损截断:若源色值本就在目标色彩空间的色域外,转换后会产生超出[0, 1]范围的值。例如,sRGB 目标下,如果源为 rgba16float,色彩空间更广(如 Display-P3),或为预乘且包含超出色域的预乘值,都可能出现上述情况。
同样,如果源值有高位深(如 16 位/分量 PNG)或扩展范围(如 float16 存储的 canvas),这些颜色会在转换过程中保留,且中间计算的精度不少于源。
3.10.2. 色彩空间转换省略
若源与目标的色彩空间/编码一致,则无需转换。通常,若某一步是恒等函数(无操作),实现应当出于性能考虑省略该步骤。
为获得最佳性能,应用应当设置色彩空间和编码选项,以最小化整个流程中所需的转换次数。
对于各种 GPUCopyExternalImageSourceInfo
图像源:
-
-
预乘由
premultiplyAlpha控制。 -
色彩空间由
colorSpaceConversion控制。
-
-
2d 画布:
-
色彩空间由
colorSpace创建上下文时的属性控制。
-
WebGL 画布:
-
预乘由
WebGLContextAttributes中的premultipliedAlpha选项控制。 -
色彩空间由
WebGLRenderingContextBase的drawingBufferColorSpace状态控制。
-
注意: 在依赖这些特性前,请检查浏览器的实现支持。
3.11. JavaScript 到 WGSL 的数值转换
WebGPU API 的多个部分(可覆盖管线 constants
和渲染通道清除值)会接收来自 WebIDL(double
或 float)的数值,并将其转换为
WGSL 值(bool、i32、u32、f32、f16)。
double
或 float
的 IDL 值 idlValue 转换为 WGSL 类型(to WGSL type) T,可能抛出 TypeError,请执行以下
设备时序 步骤:
注意: 该 TypeError
只会在 设备时序 内产生,并不会抛到
JavaScript。
-
断言 idlValue 是有限值,因为它不是
unrestricted double或unrestricted float。 -
令 v 为 将 idlValue 转换为 ECMAScript 值 后得到的 ECMAScript Number。
-
- 若 T 为
bool -
返回 WGSL
bool值,对应于 以 v 转换为 IDLboolean类型后的结果。注意: 本算法在 ECMAScript 到 IDL
double或float的转换后调用。如果原始 ECMAScript 值是非数值、非布尔类型(如[]或{}),则 WGSLbool结果可能不同于直接转换为 IDLboolean的结果。 - 若 T 为
i32 - 若 T 为
u32 - 若 T 为
f32 -
返回 WGSL
f32值,对应于 将 v 转为float的结果。 - 若 T 为
f16 -
-
令 wgslF32 为 将 v 转为
float的 WGSLf32值。 -
返回
f16(wgslF32),即将 WGSLf32值转换为f16的结果(见 WGSL 浮点数转换)。
注意: 只要值在
f32范围内,不会抛错,即使超出f16的范围。 -
- 若 T 为
GPUColor
color 转换为纹理格式的 texel 值(to a texel value of texture
format) format,可能抛出 TypeError,请执行以下
设备时序 步骤:
注意: 该 TypeError
只会在 设备时序 内产生,并不会抛到
JavaScript。
-
若 format 的各分量类型(断言全部相同)为:
- 浮点类型或归一化类型
-
令 T 为
f32。 - 有符号整型
-
令 T 为
i32。 - 无符号整型
-
令 T 为
u32。
-
令 wgslColor 为 WGSL
vec4<T>,其 4 个分量为 color 的 RGBA 通道,每个都 转换为 WGSL 类型 T。 -
按 § 23.2.7 输出合并 的同样规则将 wgslColor 转换为 format,并返回结果。
注意: 对于非整型类型,实际取值为实现定义。对于归一化类型,值会被限制在该类型允许的范围内。
注意: 换言之,写入的值就如同由 WGSL 着色器以
f32、i32 或 u32 类型的 vec4 输出。
4. Initialization
4.1. navigator.gpu
A GPU object is available
in the Window
and WorkerGlobalScope
contexts through the
Navigator
and WorkerNavigator
interfaces respectively and is exposed via navigator.gpu:
interface mixin { [NavigatorGPU SameObject ,SecureContext ]readonly attribute GPU gpu ; };Navigator includes NavigatorGPU ;WorkerNavigator includes NavigatorGPU ;
NavigatorGPU
has the following attributes:
gpu, of type GPU, readonly-
A global singleton providing top-level entry points like
requestAdapter().
4.2. GPU
GPU is
the entry point to WebGPU.
[Exposed =(Window ,Worker ),SecureContext ]interface GPU {Promise <GPUAdapter ?>requestAdapter (optional GPURequestAdapterOptions options = {});GPUTextureFormat getPreferredCanvasFormat (); [SameObject ]readonly attribute WGSLLanguageFeatures wgslLanguageFeatures ; };
GPU has the following
methods:
requestAdapter(options)-
Requests an adapter from the user agent. The user agent chooses whether to return an adapter, and, if so, chooses according to the provided options.
Called on:GPUthis.Arguments:
Arguments for the GPU.requestAdapter(options) method. Parameter Type Nullable Optional Description optionsGPURequestAdapterOptions✘ ✔ Criteria used to select the adapter. Returns:
Promise<GPUAdapter?>Content timeline steps:
-
Let contentTimeline be the current Content timeline.
-
Let promise be a new promise.
-
Issue the initialization steps on the Device timeline of this.
-
Return promise.
Device timeline initialization steps:-
All of the requirements in the following steps must be met.
-
options.
featureLevelmust be a feature level string.
If they are met and the user agent chooses to return an adapter:
-
Set adapter to an adapter chosen according to the rules in § 4.2.2 Adapter Selection and the criteria in options, adhering to § 4.2.1 Adapter Capability Guarantees. Initialize the properties of adapter according to their definitions:
-
Set adapter.
[[limits]]and adapter.[[features]]according to the supported capabilities of the adapter. adapter.[[features]]must contain"core-features-and-limits". -
If adapter meets the criteria of a fallback adapter set adapter.
[[fallback]]totrue. Otherwise, set it tofalse. -
Set adapter.
[[xrCompatible]]to options.xrCompatible.
-
Otherwise:
-
Let adapter be
null.
-
-
Issue the subsequent steps on contentTimeline.
Content timeline steps:-
If adapter is not
null:-
Resolve promise with a new
GPUAdapterencapsulating adapter.
-
-
Otherwise, Resolve promise with
null.
-
getPreferredCanvasFormat()-
Returns an optimal
GPUTextureFormatfor displaying 8-bit depth, standard dynamic range content on this system. Must only return"rgba8unorm"or"bgra8unorm".The returned value can be passed as the
formattoconfigure()calls on aGPUCanvasContextto ensure the associated canvas is able to display its contents efficiently.Note: Canvases which are not displayed to the screen may or may not benefit from using this format.
Called on:GPUthis.Returns:
GPUTextureFormatContent timeline steps:
-
Return either
"rgba8unorm"or"bgra8unorm", depending on which format is optimal for displaying WebGPU canvases on this system.
-
GPU has the following
attributes:
wgslLanguageFeatures, of type WGSLLanguageFeatures, readonly-
The names of supported WGSL language extensions. Supported language extensions are automatically enabled.
Adapters may expire at any time. Upon any change in the system’s state that
could affect
the result of any requestAdapter()
call, the user agent should expire all
previously-returned adapters. For
example:
-
A physical adapter is added/removed (via plug/unplug, driver update, hang recovery, etc.)
-
The system’s power configuration has changed (laptop unplugged, power settings changed, etc.)
Note:
User agents may choose to expire adapters often, even when there has been no system
state change (e.g. seconds or minutes after the adapter was created).
This can help obfuscate real system state changes, and make developers more aware that calling
requestAdapter()
again is always necessary before calling requestDevice().
If an application does encounter this situation, standard device-loss recovery
handling should allow it to recover.
4.2.1. Adapter Capability Guarantees
Any GPUAdapter
returned by requestAdapter()
must provide the following guarantees:
-
At least one of the following must be true:
-
"texture-compression-bc"is supported. -
Both
"texture-compression-etc2"and"texture-compression-astc"are supported.
-
-
If
"texture-compression-bc-sliced-3d"is supported, then"texture-compression-bc"must be supported. -
If
"texture-compression-astc-sliced-3d"is supported, then"texture-compression-astc"must be supported. -
All supported limits must be either the default value or better.
-
All alignment-class limits must be powers of 2.
-
maxBindingsPerBindGroupmust be must be ≥ (max bindings per shader stage × max shader stages per pipeline), where:-
max bindings per shader stage is (
maxSampledTexturesPerShaderStage+maxSamplersPerShaderStage+maxStorageBuffersPerShaderStage+maxStorageTexturesPerShaderStage+maxUniformBuffersPerShaderStage). -
max shader stages per pipeline is
2, because aGPURenderPipelinesupports both a vertex and fragment shader.
Note:
maxBindingsPerBindGroupdoes not reflect a fundamental limit; implementations should raise it to conform to this requirement, rather than lowering the other limits. -
-
maxBindGroupsmust be ≤maxBindGroupsPlusVertexBuffers. -
maxVertexBuffersmust be ≤maxBindGroupsPlusVertexBuffers. -
minUniformBufferOffsetAlignmentandminStorageBufferOffsetAlignmentmust both be ≥ 32 bytes.Note: 32 bytes would be the alignment of
vec4<f64>. See WebGPU Shading Language § 14.4.1 Alignment and Size. -
maxUniformBufferBindingSizemust be ≤maxBufferSize. -
maxStorageBufferBindingSizemust be ≤maxBufferSize. -
maxStorageBufferBindingSizemust be a multiple of 4 bytes. -
maxVertexBufferArrayStridemust be a multiple of 4 bytes. -
maxComputeWorkgroupSizeXmust be ≤maxComputeInvocationsPerWorkgroup. -
maxComputeWorkgroupSizeYmust be ≤maxComputeInvocationsPerWorkgroup. -
maxComputeWorkgroupSizeZmust be ≤maxComputeInvocationsPerWorkgroup. -
maxComputeInvocationsPerWorkgroupmust be ≤maxComputeWorkgroupSizeX×maxComputeWorkgroupSizeY×maxComputeWorkgroupSizeZ.
4.2.2. Adapter Selection
GPURequestAdapterOptions
provides hints to the user agent indicating what
configuration is suitable for the application.
dictionary GPURequestAdapterOptions {DOMString featureLevel = "core";GPUPowerPreference powerPreference ;boolean forceFallbackAdapter =false ;boolean xrCompatible =false ; };
enum {GPUPowerPreference "low-power" ,"high-performance" , };
GPURequestAdapterOptions
has the following members:
featureLevel, of type DOMString, defaulting to"core"-
"Feature level" for the adapter request.
The allowed feature level string values are:
- "core"
-
No effect.
- "compatibility"
-
No effect.
Note: This value is reserved for future use as a way to opt into additional validation restrictions. Applications should not use this value at this time.
powerPreference, of type GPUPowerPreference-
Optionally provides a hint indicating what class of adapter should be selected from the system’s available adapters.
The value of this hint may influence which adapter is chosen, but it must not influence whether an adapter is returned or not.
Note: The primary utility of this hint is to influence which GPU is used in a multi-GPU system. For instance, some laptops have a low-power integrated GPU and a high-performance discrete GPU. This hint may also affect the power configuration of the selected GPU to match the requested power preference.
Note: Depending on the exact hardware configuration, such as battery status and attached displays or removable GPUs, the user agent may select different adapters given the same power preference. Typically, given the same hardware configuration and state and
powerPreference, the user agent is likely to select the same adapter.It must be one of the following values:
undefined(or not present)-
Provides no hint to the user agent.
"low-power"-
Indicates a request to prioritize power savings over performance.
Note: Generally, content should use this if it is unlikely to be constrained by drawing performance; for example, if it renders only one frame per second, draws only relatively simple geometry with simple shaders, or uses a small HTML canvas element. Developers are encouraged to use this value if their content allows, since it may significantly improve battery life on portable devices.
"high-performance"-
Indicates a request to prioritize performance over power consumption.
Note: By choosing this value, developers should be aware that, for devices created on the resulting adapter, user agents are more likely to force device loss, in order to save power by switching to a lower-power adapter. Developers are encouraged to only specify this value if they believe it is absolutely necessary, since it may significantly decrease battery life on portable devices.
forceFallbackAdapter, of type boolean, defaulting tofalse-
When set to
trueindicates that only a fallback adapter may be returned. If the user agent does not support a fallback adapter, will causerequestAdapter()to resolve tonull.Note:
requestAdapter()may still return a fallback adapter ifforceFallbackAdapteris set tofalseand either no other appropriate adapter is available or the user agent chooses to return a fallback adapter. Developers that wish to prevent their applications from running on fallback adapters should check theinfo.isFallbackAdapterattribute prior to requesting aGPUDevice. xrCompatible, of type boolean, defaulting tofalse-
When set to
trueindicates that the best adapter for rendering to a WebXR session must be returned. If the user agent or system does not support WebXR sessions then adapter selection may ignore this value.Note: If
xrCompatibleis not set totruewhen the adapter is requested,GPUDevices created from the adapter cannot be used to render for WebXR sessions.
"high-performance"
GPUAdapter:
const gpuAdapter= await navigator. gpu. requestAdapter({ powerPreference: 'high-performance' });
4.3. GPUAdapter
A GPUAdapter
encapsulates an adapter,
and describes its capabilities (features
and limits).
To get a GPUAdapter,
use requestAdapter().
[Exposed =(Window ,Worker ),SecureContext ]interface GPUAdapter { [SameObject ]readonly attribute GPUSupportedFeatures features ; [SameObject ]readonly attribute GPUSupportedLimits limits ; [SameObject ]readonly attribute GPUAdapterInfo info ;Promise <GPUDevice >requestDevice (optional GPUDeviceDescriptor descriptor = {}); };
GPUAdapter
has the following immutable properties
features, of type GPUSupportedFeatures, readonly-
The set of values in
this.[[adapter]].[[features]]. limits, of type GPUSupportedLimits, readonly-
The limits in
this.[[adapter]].[[limits]]. info, of type GPUAdapterInfo, readonly-
Information about the physical adapter underlying this
GPUAdapter.For a given
GPUAdapter, theGPUAdapterInfovalues exposed are constant over time.The same object is returned each time. To create that object for the first time:
Called on:GPUAdapterthis.Returns:
GPUAdapterInfoContent timeline steps:
-
Return a new adapter info for this.
[[adapter]].
-
[[adapter]], of type adapter, readonly-
The adapter to which this
GPUAdapterrefers.
GPUAdapter
has the following methods:
requestDevice(descriptor)-
Requests a device from the adapter.
This is a one-time action: if a device is returned successfully, the adapter becomes
"consumed".Called on:GPUAdapterthis.Arguments:
Arguments for the GPUAdapter.requestDevice(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUDeviceDescriptor✘ ✔ Description of the GPUDeviceto request.Content timeline steps:
-
Let contentTimeline be the current Content timeline.
-
Let promise be a new promise.
-
Let adapter be this.
[[adapter]]. -
Issue the initialization steps to the Device timeline of this.
-
Return promise.
Device timeline initialization steps:-
If any of the following requirements are unmet:
-
The set of values in descriptor.
requiredFeaturesmust be a subset of those in adapter.[[features]].
Then issue the following steps on contentTimeline and return:
Content timeline steps:Note: This is the same error that is produced if a feature name isn’t known by the browser at all (in its
GPUFeatureNamedefinition). This converges the behavior when the browser doesn’t support a feature with the behavior when a particular adapter doesn’t support a feature. -
-
All of the requirements in the following steps must be met.
-
adapter.
[[state]]must not be"consumed". -
For each [key, value] in descriptor.
requiredLimitsfor which value is notundefined:-
key must be the name of a member of supported limits.
-
value must be no better than adapter.
[[limits]][key]. -
If key’s class is alignment, value must be a power of 2 less than 232.
Note: User agents should consider issuing developer-visible warnings when key is not recognized, even when value is
undefined. -
If any are unmet, issue the following steps on contentTimeline and return:
Content timeline steps:-
Reject promise with an
OperationError.
-
-
If adapter.
[[state]]is"expired"or the user agent otherwise cannot fulfill the request:-
Let device be a new device.
-
Lose the device(device,
"unknown"). -
Assert adapter.
[[state]]is"expired".Note: User agents should consider issuing developer-visible warnings in most or all cases when this occurs. Applications should perform reinitialization logic starting with
requestAdapter().
Otherwise:
-
Let device be a new device with the capabilities described by descriptor.
-
Expire adapter.
-
-
Issue the subsequent steps on contentTimeline.
Content timeline steps:-
Let gpuDevice be a new
GPUDeviceinstance. -
Set gpuDevice.
[[device]]to device. -
Set device.
[[content device]]to gpuDevice. -
Resolve promise with gpuDevice.
Note: If the device is already lost because the adapter could not fulfill the request, device.
losthas already resolved before promise resolves.
-
GPUDevice with
default features and limits:
const gpuAdapter= await navigator. gpu. requestAdapter(); const gpuDevice= await gpuAdapter. requestDevice();
4.3.1. GPUDeviceDescriptor
GPUDeviceDescriptor
describes a device request.
dictionary GPUDeviceDescriptor :GPUObjectDescriptorBase {sequence <GPUFeatureName >requiredFeatures = [];record <DOMString , (GPUSize64 or undefined )>requiredLimits = {};GPUQueueDescriptor defaultQueue = {}; };
GPUDeviceDescriptor
has the following members:
requiredFeatures, of type sequence<GPUFeatureName>, defaulting to[]-
Specifies the features that are required by the device request. The request will fail if the adapter cannot provide these features.
Exactly the specified set of features, and no more or less, will be allowed in validation of API calls on the resulting device.
requiredLimits, of typerecord<DOMString, (GPUSize64 or undefined)>, defaulting to{}-
Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
Each key with a non-
undefinedvalue must be the name of a member of supported limits.API calls on the resulting device perform validation according to the exact limits of the device (not the adapter; see § 3.6.2 Limits).
defaultQueue, of type GPUQueueDescriptor, defaulting to{}-
The descriptor for the default
GPUQueue.
GPUDevice with
the "texture-compression-astc"
feature if supported:
const gpuAdapter= await navigator. gpu. requestAdapter(); const requiredFeatures= []; if ( gpuAdapter. features. has( 'texture-compression-astc' )) { requiredFeatures. push( 'texture-compression-astc' ) } const gpuDevice= await gpuAdapter. requestDevice({ requiredFeatures});
GPUDevice with
a higher maxColorAttachmentBytesPerSample
limit:
const gpuAdapter= await navigator. gpu. requestAdapter(); if ( gpuAdapter. limits. maxColorAttachmentBytesPerSample< 64 ) { // When the desired limit isn’t supported, take action to either fall back to a code // path that does not require the higher limit or notify the user that their device // does not meet minimum requirements. } // Request higher limit of max color attachments bytes per sample. const gpuDevice= await gpuAdapter. requestDevice({ requiredLimits: { maxColorAttachmentBytesPerSample: 64 }, });
4.3.1.1. GPUFeatureName
Each GPUFeatureName
identifies a set of functionality which, if available,
allows additional usages of WebGPU that would have otherwise been invalid.
enum GPUFeatureName {"core-features-and-limits" ,"depth-clip-control" ,"depth32float-stencil8" ,"texture-compression-bc" ,"texture-compression-bc-sliced-3d" ,"texture-compression-etc2" ,"texture-compression-astc" ,"texture-compression-astc-sliced-3d" ,"timestamp-query" ,"indirect-first-instance" ,"shader-f16" ,"rg11b10ufloat-renderable" ,"bgra8unorm-storage" ,"float32-filterable" ,"float32-blendable" ,"clip-distances" ,"dual-source-blending" ,"subgroups" ,"texture-formats-tier1" ,"texture-formats-tier2" , };
4.4. GPUDevice
A GPUDevice
encapsulates a device and exposes
the functionality of that device.
GPUDevice is
the top-level interface through which WebGPU interfaces are created.
To get a GPUDevice, use
requestDevice().
[Exposed =(Window ,Worker ),SecureContext ]interface GPUDevice :EventTarget { [SameObject ]readonly attribute GPUSupportedFeatures features ; [SameObject ]readonly attribute GPUSupportedLimits limits ; [SameObject ]readonly attribute GPUAdapterInfo adapterInfo ; [SameObject ]readonly attribute GPUQueue queue ;undefined destroy ();GPUBuffer createBuffer (GPUBufferDescriptor descriptor );GPUTexture createTexture (GPUTextureDescriptor descriptor );GPUSampler createSampler (optional GPUSamplerDescriptor descriptor = {});GPUExternalTexture importExternalTexture (GPUExternalTextureDescriptor descriptor );GPUBindGroupLayout createBindGroupLayout (GPUBindGroupLayoutDescriptor descriptor );GPUPipelineLayout createPipelineLayout (GPUPipelineLayoutDescriptor descriptor );GPUBindGroup createBindGroup (GPUBindGroupDescriptor descriptor );GPUShaderModule createShaderModule (GPUShaderModuleDescriptor descriptor );GPUComputePipeline createComputePipeline (GPUComputePipelineDescriptor descriptor );GPURenderPipeline createRenderPipeline (GPURenderPipelineDescriptor descriptor );Promise <GPUComputePipeline >createComputePipelineAsync (GPUComputePipelineDescriptor descriptor );Promise <GPURenderPipeline >createRenderPipelineAsync (GPURenderPipelineDescriptor descriptor );GPUCommandEncoder createCommandEncoder (optional GPUCommandEncoderDescriptor descriptor = {});GPURenderBundleEncoder createRenderBundleEncoder (GPURenderBundleEncoderDescriptor descriptor );GPUQuerySet createQuerySet (GPUQuerySetDescriptor descriptor ); };GPUDevice includes GPUObjectBase ;
GPUDevice has
the following immutable
properties:
features, of type GPUSupportedFeatures, readonly-
A set containing the
GPUFeatureNamevalues of the features supported by the device ([[device]].[[features]]). limits, of type GPUSupportedLimits, readonly-
The limits supported by the device (
[[device]].[[limits]]). queue, of type GPUQueue, readonly-
The primary
GPUQueuefor this device. adapterInfo, of type GPUAdapterInfo, readonly-
Information about the physical adapter which created the device that this
GPUDevicerefers to.For a given
GPUDevice, theGPUAdapterInfovalues exposed are constant over time.The same object is returned each time. To create that object for the first time:
Called on:GPUDevicethis.Returns:
GPUAdapterInfoContent timeline steps:
-
Return a new adapter info for this.
[[device]].[[adapter]].
-
The [[device]]
for a GPUDevice is
the device that the GPUDevice
refers
to.
GPUDevice has
the following methods:
destroy()-
Destroys the device, preventing further operations on it. Outstanding asynchronous operations will fail.
Note: It is valid to destroy a device multiple times.
Called on:GPUDevicethis.Content timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
-
Lose the device(this.
[[device]],"destroyed").
Note: Since no further operations can be enqueued on this device, implementations can abort outstanding asynchronous operations immediately and free resource allocations, including mapped memory that was just unmapped.
GPUDevice’s
allowed buffer
usages are:
GPUDevice’s
allowed texture
usages are:
-
Always allowed:
COPY_SRC,COPY_DST,TEXTURE_BINDING,STORAGE_BINDING,RENDER_ATTACHMENT
4.5. Example
GPUAdapter
and GPUDevice with
error handling:
let gpuDevice= null ; async function initializeWebGPU() { // Check to ensure the user agent supports WebGPU. if ( ! ( 'gpu' in navigator)) { console. error( "User agent doesn’t support WebGPU." ); return false ; } // Request an adapter. const gpuAdapter= await navigator. gpu. requestAdapter(); // requestAdapter may resolve with null if no suitable adapters are found. if ( ! gpuAdapter) { console. error( 'No WebGPU adapters found.' ); return false ; } // Request a device. // Note that the promise will reject if invalid options are passed to the optional // dictionary. To avoid the promise rejecting always check any features and limits // against the adapters features and limits prior to calling requestDevice(). gpuDevice= await gpuAdapter. requestDevice(); // requestDevice will never return null, but if a valid device request can’t be // fulfilled for some reason it may resolve to a device which has already been lost. // Additionally, devices can be lost at any time after creation for a variety of reasons // (ie: browser resource management, driver updates), so it’s a good idea to always // handle lost devices gracefully. gpuDevice. lost. then(( info) => { console. error( `WebGPU device was lost: ${ info. message} ` ); gpuDevice= null ; // Many causes for lost devices are transient, so applications should try getting a // new device once a previous one has been lost unless the loss was caused by the // application intentionally destroying the device. Note that any WebGPU resources // created with the previous device (buffers, textures, etc) will need to be // re-created with the new one. if ( info. reason!= 'destroyed' ) { initializeWebGPU(); } }); onWebGPUInitialized(); return true ; } function onWebGPUInitialized() { // Begin creating WebGPU resources here... } initializeWebGPU();
5. Buffers
5.1. GPUBuffer
A GPUBuffer
represents a block of memory that can be used in GPU operations.
Data is stored in linear layout, meaning that each byte of the allocation can be
addressed by its offset from the start of the GPUBuffer,
subject to alignment
restrictions depending on the operation. Some GPUBuffers can
be
mapped which makes the block of memory accessible via an ArrayBuffer
called
its mapping.
GPUBuffers
are created via createBuffer().
Buffers may be mappedAtCreation.
[Exposed =(Window ,Worker ),SecureContext ]interface GPUBuffer {readonly attribute GPUSize64Out size ;readonly attribute GPUFlagsConstant usage ;readonly attribute GPUBufferMapState mapState ;Promise <undefined >mapAsync (GPUMapModeFlags mode ,optional GPUSize64 offset = 0,optional GPUSize64 size );ArrayBuffer getMappedRange (optional GPUSize64 offset = 0,optional GPUSize64 size );undefined unmap ();undefined destroy (); };GPUBuffer includes GPUObjectBase ;enum GPUBufferMapState {"unmapped" ,"pending" ,"mapped" , };
GPUBuffer has
the following immutable
properties:
size, of type GPUSize64Out, readonly-
The length of the
GPUBufferallocation in bytes. usage, of type GPUFlagsConstant, readonly-
The allowed usages for this
GPUBuffer.
GPUBuffer has
the following content timeline properties:
mapState, of type GPUBufferMapState, readonly-
The current
GPUBufferMapStateof the buffer:"unmapped"-
The buffer is not mapped for use by
this.getMappedRange(). "pending"-
A mapping of the buffer has been requested, but is pending. It may succeed, or fail validation in
mapAsync(). "mapped"-
The buffer is mapped and
this.getMappedRange()may be used.
The getter steps are:
Content timeline steps:-
If this.
[[mapping]]is notnull, return"mapped". -
If this.
[[pending_map]]is notnull, return"pending". -
Return
"unmapped".
[[pending_map]], of typePromise<void> ornull, initiallynull-
The
Promisereturned by the currently-pendingmapAsync()call.There is never more than one pending map, because
mapAsync()will refuse immediately if a request is already in flight. [[mapping]], of type active buffer mapping ornull, initiallynull-
Set if and only if the buffer is currently mapped for use by
getMappedRange(). Null otherwise (even if there is a[[pending_map]]).An active buffer mapping is a structure with the following fields:
- data, of type Data Block
-
The mapping for this
GPUBuffer. This data is accessed throughArrayBuffers which are views onto this data, returned bygetMappedRange()and stored in views. - mode, of type
GPUMapModeFlags -
The
GPUMapModeFlagsof the map, as specified in the corresponding call tomapAsync()orcreateBuffer(). - range, of type tuple [
unsigned long long,unsigned long long] -
The range of this
GPUBufferthat is mapped. - views, of type list<
ArrayBuffer> -
The
ArrayBuffers returned viagetMappedRange()to the application. They are tracked so they can be detached whenunmap()is called.
To initialize an active buffer mapping with mode mode and range range, run the following content timeline steps:-
Let size be range[1] - range[0].
-
Let data be ? CreateByteDataBlock(size).
NOTE:This may result in aRangeErrorbeing thrown. For consistency and predictability:-
For any size at which
new ArrayBuffer()would succeed at a given moment, this allocation should succeed at that moment. -
For any size at which
new ArrayBuffer()deterministically throws aRangeError, this allocation should as well.
-
-
Return an active buffer mapping with:
GPUBuffer has
the following device timeline properties:
[[internal state]]-
The current internal state of the buffer:
5.1.1. GPUBufferDescriptor
dictionary GPUBufferDescriptor :GPUObjectDescriptorBase {required GPUSize64 size ;required GPUBufferUsageFlags usage ;boolean mappedAtCreation =false ; };
GPUBufferDescriptor
has the following members:
size, of type GPUSize64-
The size of the buffer in bytes.
usage, of type GPUBufferUsageFlags-
The allowed usages for the buffer.
mappedAtCreation, of type boolean, defaulting tofalse-
If
truecreates the buffer in an already mapped state, allowinggetMappedRange()to be called immediately. It is valid to setmappedAtCreationtotrueeven ifusagedoes not containMAP_READorMAP_WRITE. This can be used to set the buffer’s initial data.Guarantees that even if the buffer creation eventually fails, it will still appear as if the mapped range can be written/read to until it is unmapped.
5.1.2. Buffer Usages
typedef [EnforceRange ]unsigned long ; [GPUBufferUsageFlags Exposed =(Window ,Worker ),SecureContext ]namespace {GPUBufferUsage const GPUFlagsConstant MAP_READ = 0x0001;const GPUFlagsConstant MAP_WRITE = 0x0002;const GPUFlagsConstant COPY_SRC = 0x0004;const GPUFlagsConstant COPY_DST = 0x0008;const GPUFlagsConstant INDEX = 0x0010;const GPUFlagsConstant VERTEX = 0x0020;const GPUFlagsConstant UNIFORM = 0x0040;const GPUFlagsConstant STORAGE = 0x0080;const GPUFlagsConstant INDIRECT = 0x0100;const GPUFlagsConstant QUERY_RESOLVE = 0x0200; };
The GPUBufferUsage
flags determine how a GPUBuffer may
be used after its creation:
MAP_READ-
The buffer can be mapped for reading. (Example: calling
mapAsync()withGPUMapMode.READ)May only be combined with
COPY_DST. MAP_WRITE-
The buffer can be mapped for writing. (Example: calling
mapAsync()withGPUMapMode.WRITE)May only be combined with
COPY_SRC. COPY_SRC-
The buffer can be used as the source of a copy operation. (Examples: as the
sourceargument of a copyBufferToBuffer() orcopyBufferToTexture()call.) COPY_DST-
The buffer can be used as the destination of a copy or write operation. (Examples: as the
destinationargument of a copyBufferToBuffer() orcopyTextureToBuffer()call, or as the target of awriteBuffer()call.) INDEX-
The buffer can be used as an index buffer. (Example: passed to
setIndexBuffer().) VERTEX-
The buffer can be used as a vertex buffer. (Example: passed to
setVertexBuffer().) UNIFORM-
The buffer can be used as a uniform buffer. (Example: as a bind group entry for a
GPUBufferBindingLayoutwith abuffer.typeof"uniform".) STORAGE-
The buffer can be used as a storage buffer. (Example: as a bind group entry for a
GPUBufferBindingLayoutwith abuffer.typeof"storage"or"read-only-storage".) INDIRECT-
The buffer can be used as to store indirect command arguments. (Examples: as the
indirectBufferargument of adrawIndirect()ordispatchWorkgroupsIndirect()call.) QUERY_RESOLVE-
The buffer can be used to capture query results. (Example: as the
destinationargument of aresolveQuerySet()call.)
5.1.3. Buffer Creation
createBuffer(descriptor)-
Creates a
GPUBuffer.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createBuffer(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUBufferDescriptor✘ ✘ Description of the GPUBufferto create.Returns:
GPUBufferContent timeline steps:
-
Let b be ! create a new WebGPU object(this,
GPUBuffer, descriptor). -
If descriptor.
mappedAtCreationistrue:-
If descriptor.
sizeis not a multiple of 4, throw aRangeError. -
Set b.
[[mapping]]to ? initialize an active buffer mapping with modeWRITEand range[0, descriptor..size]
-
-
Issue the initialization steps on the Device timeline of this.
-
Return b.
Device timeline initialization steps:-
If any of the following requirements are unmet, generate a validation error, invalidate b and return.
-
this must not be lost.
-
descriptor.
usagemust not be 0. -
descriptor.
usagemust be a subset of the allowed buffer usages for this. -
If descriptor.
sizemust be ≤ this.[[device]].[[limits]].maxBufferSize.
-
Note: If buffer creation fails, and descriptor.
mappedAtCreationisfalse, any calls tomapAsync()will reject, so any resources allocated to enable mapping can and may be discarded or recycled.-
If descriptor.
mappedAtCreationistrue:-
Set b.
[[internal state]]to "unavailable".
Else:
-
Set b.
[[internal state]]to "available".
-
-
Create a device allocation for b where each byte is zero.
If the allocation fails without side-effects, generate an out-of-memory error, invalidate b, and return.
-
const buffer= gpuDevice. createBuffer({ size: 128 , usage: GPUBufferUsage. UNIFORM| GPUBufferUsage. COPY_DST});
5.1.4. Buffer Destruction
An application that no longer requires a GPUBuffer can
choose to lose
access to it before garbage collection by calling destroy().
Destroying a buffer also
unmaps it, freeing any memory allocated for the mapping.
Note: This allows the user agent to reclaim the GPU
memory associated with the GPUBuffer
once all previously submitted operations using it are complete.
GPUBuffer has
the following methods:
destroy()-
Destroys the
GPUBuffer.Note: It is valid to destroy a buffer multiple times.
Called on:GPUBufferthis.Returns:
undefinedContent timeline steps:
-
Call this.
unmap(). -
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Set this.
[[internal state]]to "destroyed".
Note: Since no further operations can be enqueued using this buffer, implementations can free resource allocations, including mapped memory that was just unmapped.
-
5.2. Buffer Mapping
An application can request to map a GPUBuffer so
that they can access its
content via ArrayBuffers
that represent part of the GPUBuffer’s
allocations. Mapping a GPUBuffer is
requested asynchronously with
mapAsync()
so that the user agent can ensure the GPU
finished using the GPUBuffer
before the application can access its content.
A mapped GPUBuffer
cannot be used by the GPU and must be unmapped using unmap()
before
work using it can be submitted to the Queue timeline.
Once the GPUBuffer is
mapped, the application can synchronously ask for access
to ranges of its content with getMappedRange().
The returned ArrayBuffer
can only be detached by unmap()
(directly, or via GPUBuffer.destroy()
or GPUDevice.destroy()),
and cannot be transferred.
A TypeError
is thrown by any other operation that attempts to do so.
typedef [EnforceRange ]unsigned long ; [GPUMapModeFlags Exposed =(Window ,Worker ),SecureContext ]namespace {GPUMapMode const GPUFlagsConstant READ = 0x0001;const GPUFlagsConstant WRITE = 0x0002; };
The GPUMapMode
flags determine how a GPUBuffer is
mapped when calling
mapAsync():
READ-
Only valid with buffers created with the
MAP_READusage.Once the buffer is mapped, calls to
getMappedRange()will return anArrayBuffercontaining the buffer’s current values. Changes to the returnedArrayBufferwill be discarded afterunmap()is called. WRITE-
Only valid with buffers created with the
MAP_WRITEusage.Once the buffer is mapped, calls to
getMappedRange()will return anArrayBuffercontaining the buffer’s current values. Changes to the returnedArrayBufferwill be stored in theGPUBufferafterunmap()is called.Note: Since the
MAP_WRITEbuffer usage may only be combined with theCOPY_SRCbuffer usage, mapping for writing can never return values produced by the GPU, and the returnedArrayBufferwill only ever contain the default initialized data (zeros) or data written by the webpage during a previous mapping.
GPUBuffer has
the following methods:
mapAsync(mode, offset, size)-
Maps the given range of the
GPUBufferand resolves the returnedPromisewhen theGPUBuffer’s content is ready to be accessed withgetMappedRange().The resolution of the returned
Promiseonly indicates that the buffer has been mapped. It does not guarantee the completion of any other operations visible to the content timeline, and in particular does not imply that any otherPromisereturned fromonSubmittedWorkDone()ormapAsync()on otherGPUBuffers have resolved.The resolution of the
Promisereturned fromonSubmittedWorkDone()does imply the completion ofmapAsync()calls made prior to that call, onGPUBuffers last used exclusively on that queue.Called on:GPUBufferthis.Arguments:
Arguments for the GPUBuffer.mapAsync(mode, offset, size) method. Parameter Type Nullable Optional Description modeGPUMapModeFlags✘ ✘ Whether the buffer should be mapped for reading or writing. offsetGPUSize64✘ ✔ Offset in bytes into the buffer to the start of the range to map. sizeGPUSize64✘ ✔ Size in bytes of the range to map. Content timeline steps:
-
Let contentTimeline be the current Content timeline.
-
If this.
mapStateis not"unmapped":-
Issue the early-reject steps on the Device timeline of this.
[[device]].
-
-
Let p be a new
Promise. -
Set this.
[[pending_map]]to p. -
Issue the validation steps on the Device timeline of this.
[[device]]. -
Return p.
Device timeline early-reject steps:-
Return.
Device timeline validation steps:-
If size is
undefined:-
Let rangeSize be max(0, this.
size- offset).
Otherwise:
-
Let rangeSize be size.
-
-
If any of the following conditions are unsatisfied:
-
this must be valid.
-
Set deviceLost to
true. -
Issue the map failure steps on contentTimeline.
-
Return.
-
-
If any of the following conditions are unsatisfied:
-
this.
[[internal state]]is "available". -
offset is a multiple of 8.
-
rangeSize is a multiple of 4.
-
offset + rangeSize ≤ this.
size -
mode contains only bits defined in
GPUMapMode. -
If mode contains
READthen this.usagemust containMAP_READ. -
If mode contains
WRITEthen this.usagemust containMAP_WRITE.
Then:
-
Set deviceLost to
false. -
Issue the map failure steps on contentTimeline.
-
Return.
-
-
Set this.
[[internal state]]to "unavailable".Note: Since the buffer is mapped, its contents cannot change between this step and
unmap(). -
When either of the following events occur (whichever comes first), or if either has already occurred:
-
The device timeline becomes informed of the completion of an unspecified queue timeline point:
-
after the completion of currently-enqueued operations that use this
-
and no later than the completion of all currently-enqueued operations (regardless of whether they use this).
-
-
this.
[[device]]becomes lost.
Then issue the subsequent steps on the device timeline of this.
[[device]]. -
Device timeline steps:-
Set deviceLost to
trueif this.[[device]]is lost, andfalseotherwise.Note: The device could have been lost between the previous block of steps and this one.
-
If deviceLost:
-
Issue the map failure steps on contentTimeline.
Otherwise:
-
Let internalStateAtCompletion be this.
[[internal state]].Note: If, and only if, at this point the buffer has become "available" again due to an
unmap()call, then[[pending_map]]!= p below, so mapping will not succeed in the steps below. -
Let dataForMappedRegion be the contents of this starting at offset offset, for rangeSize bytes.
-
Issue the map success steps on the contentTimeline.
-
Content timeline map success steps:-
If this.
[[pending_map]]!= p:Note: The map has been cancelled by
unmap().-
Assert p is rejected.
-
Return.
-
-
Assert p is pending.
-
Assert internalStateAtCompletion is "unavailable".
-
Let mapping be initialize an active buffer mapping with mode mode and range
[offset, offset + rangeSize].If this allocation fails:
-
Set this.
[[pending_map]]tonull, and reject p with aRangeError. -
Return.
-
-
Set the content of mapping.data to dataForMappedRegion.
-
Set this.
[[mapping]]to mapping. -
Set this.
[[pending_map]]tonull, and resolve p.
Content timeline map failure steps:-
If this.
[[pending_map]]!= p:Note: The map has been cancelled by
unmap().-
Assert p is already rejected.
-
Return.
-
-
Assert p is still pending.
-
Set this.
[[pending_map]]tonull. -
If deviceLost:
-
Reject p with an
AbortError.Note: This is the same error type produced by cancelling the map using
unmap().
Otherwise:
-
Reject p with an
OperationError.
-
-
getMappedRange(offset, size)-
Returns an
ArrayBufferwith the contents of theGPUBufferin the given mapped range.Called on:GPUBufferthis.Arguments:
Arguments for the GPUBuffer.getMappedRange(offset, size) method. Parameter Type Nullable Optional Description offsetGPUSize64✘ ✔ Offset in bytes into the buffer to return buffer contents from. sizeGPUSize64✘ ✔ Size in bytes of the ArrayBufferto return.Returns:
ArrayBufferContent timeline steps:
-
If size is missing:
-
Let rangeSize be max(0, this.
size- offset).
Otherwise, let rangeSize be size.
-
-
If any of the following conditions are unsatisfied, throw an
OperationErrorand return.-
this.
[[mapping]]is notnull. -
offset is a multiple of 8.
-
rangeSize is a multiple of 4.
-
offset ≥ this.
[[mapping]].range[0]. -
offset + rangeSize ≤ this.
[[mapping]].range[1]. -
[offset, offset + rangeSize) does not overlap another range in this.
[[mapping]].views.
Note: It is always valid to get mapped ranges of a
GPUBufferthat ismappedAtCreation, even if it is invalid, because the Content timeline might not know it is invalid. -
-
Let data be this.
[[mapping]].data. -
Let view be ! create an ArrayBuffer of size rangeSize, but with its pointer mutably referencing the content of data at offset (offset -
[[mapping]].range[0]).Note: A
RangeErrormay not be thrown here, because the data has already been allocated duringmapAsync()orcreateBuffer(). -
Set view.
[[ArrayBufferDetachKey]]to "WebGPUBufferMapping".Note: This causes a
TypeErrorto be thrown if an attempt is made to DetachArrayBuffer, except byunmap(). -
Append view to this.
[[mapping]].views. -
Return view.
Note: User agents should consider issuing a developer-visible warning if
getMappedRange()succeeds without having checked the status of the map, by waiting formapAsync()to succeed, querying amapStateof"mapped", or waiting for a lateronSubmittedWorkDone()call to succeed. -
unmap()-
Unmaps the mapped range of the
GPUBufferand makes its contents available for use by the GPU again.Called on:GPUBufferthis.Returns:
undefinedContent timeline steps:
-
If this.
[[pending_map]]is notnull:-
Reject this.
[[pending_map]]with anAbortError. -
Set this.
[[pending_map]]tonull.
-
-
If this.
[[mapping]]isnull:-
Return.
-
-
For each
ArrayBufferab in this.[[mapping]].views:-
Perform DetachArrayBuffer(ab, "WebGPUBufferMapping").
-
-
Let bufferUpdate be
null. -
If this.
[[mapping]].mode containsWRITE:-
Set bufferUpdate to {
data: this.[[mapping]].data,offset: this.[[mapping]].range[0] }.
Note: When a buffer is mapped without the
WRITEmode, then unmapped, any local modifications done by the application to the mapped rangesArrayBufferare discarded and will not affect the content of later mappings. -
-
Set this.
[[mapping]]tonull. -
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
If any of the following conditions are unsatisfied, return.
-
this is valid to use with this.
[[device]].
-
-
Assert this.
[[internal state]]is "unavailable". -
If bufferUpdate is not
null:-
Issue the following steps on the Queue timeline of this.
[[device]].queue:Queue timeline steps:-
Update the contents of this at offset bufferUpdate.
offsetwith the data bufferUpdate.data.
-
-
-
Set this.
[[internal state]]to "available".
-
6. Textures and Texture Views
6.1. GPUTexture
A texture is made up of 1d,
2d,
or 3d
arrays of data which can contain multiple values per-element to
represent things like colors. Textures can be read and written in many ways, depending on the
GPUTextureUsage
they are created with. For example, textures can be sampled, read, and written
from render and compute pipeline shaders, and they can be written by render pass outputs.
Internally, textures are often stored in GPU memory with a layout optimized for
multidimensional access rather than linear access.
One texture consists of one or more texture
subresources,
each uniquely identified by a mipmap
level and,
for 2d
textures only, array layer and aspect.
A texture subresource is a subresource: each can be used in different internal usages within a single usage scope.
Each subresource in a mipmap
level is approximately half the size,
in each spatial dimension, of the corresponding resource in the lesser level
(see logical miplevel-specific texture extent).
The subresource in level 0 has the dimensions of the texture itself.
Smaller levels are typically used to store lower resolution versions of the same image.
GPUSampler
and WGSL provide facilities for selecting and interpolating between levels of detail, explicitly or
automatically.
A "2d"
texture may be an array of array
layers.
Each subresource in a layer is the same size as the corresponding resources in other layers.
For non-2d textures, all subresources have an array layer index of 0.
Each subresource has an aspect.
Color textures have just one aspect: color.
Depth-or-stencil format textures may have multiple aspects:
a depth aspect,
a stencil aspect, or both, and may be used in special ways, such as in
depthStencilAttachment
and in "depth"
bindings.
A "3d"
texture may have multiple slices, each being the
two-dimensional image at a particular z value in the texture.
Slices are not separate subresources.
[Exposed =(Window ,Worker ),SecureContext ]interface GPUTexture {GPUTextureView createView (optional GPUTextureViewDescriptor descriptor = {});undefined destroy ();readonly attribute GPUIntegerCoordinateOut width ;readonly attribute GPUIntegerCoordinateOut height ;readonly attribute GPUIntegerCoordinateOut depthOrArrayLayers ;readonly attribute GPUIntegerCoordinateOut mipLevelCount ;readonly attribute GPUSize32Out sampleCount ;readonly attribute GPUTextureDimension dimension ;readonly attribute GPUTextureFormat format ;readonly attribute GPUFlagsConstant usage ; };GPUTexture includes GPUObjectBase ;
GPUTexture
has the following immutable properties:
width, of type GPUIntegerCoordinateOut, readonly-
The width of this
GPUTexture. height, of type GPUIntegerCoordinateOut, readonly-
The height of this
GPUTexture. depthOrArrayLayers, of type GPUIntegerCoordinateOut, readonly-
The depth or layer count of this
GPUTexture. mipLevelCount, of type GPUIntegerCoordinateOut, readonly-
The number of mip levels of this
GPUTexture. sampleCount, of type GPUSize32Out, readonly-
The number of sample count of this
GPUTexture. dimension, of type GPUTextureDimension, readonly-
The dimension of the set of texel for each of this
GPUTexture’s subresources. format, of type GPUTextureFormat, readonly-
The format of this
GPUTexture. usage, of type GPUFlagsConstant, readonly-
The allowed usages for this
GPUTexture. [[viewFormats]], of type sequence<GPUTextureFormat>-
The set of
GPUTextureFormats that can be used as theGPUTextureViewDescriptor.formatwhen creating views on thisGPUTexture.
GPUTexture
has the following device timeline properties:
[[destroyed]], of typeboolean, initiallyfalse-
If the texture is destroyed, it can no longer be used in any operation, and its underlying memory can be freed.
Arguments:
-
GPUExtent3DbaseSize -
GPUSize32mipLevel
Returns: GPUExtent3DDict
Device timeline steps:
-
Let extent be a new
GPUExtent3DDictobject. -
Set extent.
depthOrArrayLayersto 1. -
Return extent.
The logical miplevel-specific texture extent of a texture is the size of the texture in texels at a specific miplevel. It is calculated by this procedure:
Arguments:
-
GPUTextureDescriptordescriptor -
GPUSize32mipLevel
Returns: GPUExtent3DDict
-
Let extent be a new
GPUExtent3DDictobject. -
If descriptor.
dimensionis:"1d"-
-
Set extent.
widthto max(1, descriptor.size.width ≫ mipLevel). -
Set extent.
heightto 1. -
Set extent.
depthOrArrayLayersto 1.
-
"2d"-
-
Set extent.
widthto max(1, descriptor.size.width ≫ mipLevel). -
Set extent.
heightto max(1, descriptor.size.height ≫ mipLevel). -
Set extent.
depthOrArrayLayersto descriptor.size.depthOrArrayLayers.
-
"3d"-
-
Set extent.
widthto max(1, descriptor.size.width ≫ mipLevel). -
Set extent.
heightto max(1, descriptor.size.height ≫ mipLevel). -
Set extent.
depthOrArrayLayersto max(1, descriptor.size.depthOrArrayLayers ≫ mipLevel).
-
-
Return extent.
The physical miplevel-specific texture extent of a texture is the size of the texture in texels at a specific miplevel that includes the possible extra padding to form complete texel blocks in the texture. It is calculated by this procedure:
Arguments:
-
GPUTextureDescriptordescriptor -
GPUSize32mipLevel
Returns: GPUExtent3DDict
-
Let extent be a new
GPUExtent3DDictobject. -
Let logicalExtent be logical miplevel-specific texture extent(descriptor, mipLevel).
-
If descriptor.
dimensionis:"1d"-
-
Set extent.
widthto logicalExtent.width rounded up to the nearest multiple of descriptor’s texel block width. -
Set extent.
heightto 1. -
Set extent.
depthOrArrayLayersto 1.
-
"2d"-
-
Set extent.
widthto logicalExtent.width rounded up to the nearest multiple of descriptor’s texel block width. -
Set extent.
heightto logicalExtent.height rounded up to the nearest multiple of descriptor’s texel block height. -
Set extent.
depthOrArrayLayersto logicalExtent.depthOrArrayLayers.
-
"3d"-
-
Set extent.
widthto logicalExtent.width rounded up to the nearest multiple of descriptor’s texel block width. -
Set extent.
heightto logicalExtent.height rounded up to the nearest multiple of descriptor’s texel block height. -
Set extent.
depthOrArrayLayersto logicalExtent.depthOrArrayLayers.
-
-
Return extent.
6.1.1. GPUTextureDescriptor
dictionary GPUTextureDescriptor :GPUObjectDescriptorBase {required GPUExtent3D size ;GPUIntegerCoordinate mipLevelCount = 1;GPUSize32 sampleCount = 1;GPUTextureDimension dimension = "2d";required GPUTextureFormat format ;required GPUTextureUsageFlags usage ;sequence <GPUTextureFormat >viewFormats = []; };
GPUTextureDescriptor
has the following members:
size, of type GPUExtent3D-
The width, height, and depth or layer count of the texture.
mipLevelCount, of type GPUIntegerCoordinate, defaulting to1-
The number of mip levels the texture will contain.
sampleCount, of type GPUSize32, defaulting to1-
The sample count of the texture. A
sampleCount>1indicates a multisampled texture. dimension, of type GPUTextureDimension, defaulting to"2d"-
Whether the texture is one-dimensional, an array of two-dimensional layers, or three-dimensional.
format, of type GPUTextureFormat-
The format of the texture.
usage, of type GPUTextureUsageFlags-
The allowed usages for the texture.
viewFormats, of type sequence<GPUTextureFormat>, defaulting to[]-
Specifies what view
formatvalues will be allowed when callingcreateView()on this texture (in addition to the texture’s actualformat).NOTE:Adding a format to this list may have a significant performance impact, so it is best to avoid adding formats unnecessarily.The actual performance impact is highly dependent on the target system; developers must test various systems to find out the impact on their particular application. For example, on some systems any texture with a
formatorviewFormatsentry including"rgba8unorm-srgb"will perform less optimally than a"rgba8unorm"texture which does not. Similar caveats exist for other formats and pairs of formats on other systems.Formats in this list must be texture view format compatible with the texture format.
TwoGPUTextureFormats format and viewFormat are texture view format compatible if:-
format equals viewFormat, or
-
format and viewFormat differ only in whether they are
srgbformats (have the-srgbsuffix).
-
enum {GPUTextureDimension "1d" ,"2d" ,"3d" , };
"1d"-
Specifies a texture that has one dimension, width.
"1d"textures cannot have mipmaps, be multisampled, use compressed or depth/stencil formats, or be used as a render target. "2d"-
Specifies a texture that has a width and height, and may have layers.
"3d"-
Specifies a texture that has a width, height, and depth.
"3d"textures cannot be multisampled, and their format must support 3d textures (all plain color formats and some packed/compressed formats).
6.1.2. Texture Usages
typedef [EnforceRange ]unsigned long ; [GPUTextureUsageFlags Exposed =(Window ,Worker ),SecureContext ]namespace {GPUTextureUsage const GPUFlagsConstant COPY_SRC = 0x01;const GPUFlagsConstant COPY_DST = 0x02;const GPUFlagsConstant TEXTURE_BINDING = 0x04;const GPUFlagsConstant STORAGE_BINDING = 0x08;const GPUFlagsConstant RENDER_ATTACHMENT = 0x10; };
The GPUTextureUsage
flags determine how a GPUTexture
may be used after its creation:
COPY_SRC-
The texture can be used as the source of a copy operation. (Examples: as the
sourceargument of acopyTextureToTexture()orcopyTextureToBuffer()call.) COPY_DST-
The texture can be used as the destination of a copy or write operation. (Examples: as the
destinationargument of acopyTextureToTexture()orcopyBufferToTexture()call, or as the target of awriteTexture()call.) TEXTURE_BINDING-
The texture can be bound for use as a sampled texture in a shader (Example: as a bind group entry for a
GPUTextureBindingLayout.) STORAGE_BINDING-
The texture can be bound for use as a storage texture in a shader (Example: as a bind group entry for a
GPUStorageTextureBindingLayout.) RENDER_ATTACHMENT-
The texture can be used as a color or depth/stencil attachment in a render pass. (Example: as a
GPURenderPassColorAttachment.vieworGPURenderPassDepthStencilAttachment.view.)
Arguments:
-
GPUTextureDimensiondimension -
GPUTextureDimensionsize
6.1.3. Texture Creation
createTexture(descriptor)-
Creates a
GPUTexture.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createTexture(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUTextureDescriptor✘ ✘ Description of the GPUTextureto create.Returns:
GPUTextureContent timeline steps:
-
? validate GPUExtent3D shape(descriptor.
size). -
? Validate texture format required features of descriptor.
formatwith this.[[device]]. -
? Validate texture format required features of each element of descriptor.
viewFormatswith this.[[device]]. -
Let t be ! create a new WebGPU object(this,
GPUTexture, descriptor). -
Set t.
depthOrArrayLayersto descriptor.size.depthOrArrayLayers. -
Set t.
mipLevelCountto descriptor.mipLevelCount. -
Set t.
sampleCountto descriptor.sampleCount. -
Issue the initialization steps on the Device timeline of this.
-
Return t.
Device timeline initialization steps:-
If any of the following conditions are unsatisfied generate a validation error, invalidate t and return.
-
validating GPUTextureDescriptor(this, descriptor) returns
true.
-
-
Set t.
[[viewFormats]]to descriptor.viewFormats. -
Create a device allocation for t where each block has an equivalent texel representation to a block with a bit representation of zero.
If the allocation fails without side-effects, generate an out-of-memory error, invalidate t, and return.
-
Arguments:
-
GPUDevicethis -
GPUTextureDescriptordescriptor
Device timeline steps:
-
Let limits be this.
[[limits]]. -
Return
trueif all of the following requirements are met, andfalseotherwise:-
this must not be lost.
-
descriptor.
usagemust not be 0. -
descriptor.
usagemust contain only bits present in this’s allowed texture usages. -
descriptor.
size.width, descriptor.size.height, and descriptor.size.depthOrArrayLayers must be > zero. -
descriptor.
mipLevelCountmust be > zero. -
descriptor.
sampleCountmust be either 1 or 4. -
If descriptor.
dimensionis:"1d"-
-
descriptor.
size.width must be ≤ limits.maxTextureDimension1D. -
descriptor.
size.depthOrArrayLayers must be 1. -
descriptor.
sampleCountmust be 1. -
descriptor.
formatmust not be a compressed format or depth-or-stencil format.
-
"2d"-
-
descriptor.
size.width must be ≤ limits.maxTextureDimension2D. -
descriptor.
size.height must be ≤ limits.maxTextureDimension2D. -
descriptor.
size.depthOrArrayLayers must be ≤ limits.maxTextureArrayLayers.
-
"3d"-
-
descriptor.
size.width must be ≤ limits.maxTextureDimension3D. -
descriptor.
size.height must be ≤ limits.maxTextureDimension3D. -
descriptor.
size.depthOrArrayLayers must be ≤ limits.maxTextureDimension3D. -
descriptor.
sampleCountmust be 1. -
descriptor.
formatmust support"3d"textures according to § 26.1 Texture Format Capabilities.
-
-
descriptor.
size.width must be multiple of texel block width. -
descriptor.
size.height must be multiple of texel block height. -
If descriptor.
sampleCount> 1:-
descriptor.
mipLevelCountmust be 1. -
descriptor.
size.depthOrArrayLayers must be 1. -
descriptor.
usagemust not include theSTORAGE_BINDINGbit. -
descriptor.
usagemust include theRENDER_ATTACHMENTbit. -
descriptor.
formatmust support multisampling according to § 26.1 Texture Format Capabilities.
-
-
descriptor.
mipLevelCountmust be ≤ maximum mipLevel count(descriptor.dimension, descriptor.size). -
If descriptor.
usageincludes theRENDER_ATTACHMENTbit:-
descriptor.
formatmust be a renderable format.
-
-
If descriptor.
usageincludes theSTORAGE_BINDINGbit:-
descriptor.
formatmust be listed in § 26.1.1 Plain color formats table withSTORAGE_BINDINGcapability for at least one access mode.
-
-
For each viewFormat in descriptor.
viewFormats, descriptor.formatand viewFormat must be texture view format compatible.NOTE:Implementations may consider issuing a developer-visible warning if viewFormat is not compatible with any of the givenusagebits, as that viewFormat will be unusable.
-
const texture= gpuDevice. createTexture({ size: { width: 16 , height: 16 }, format: 'rgba8unorm' , usage: GPUTextureUsage. TEXTURE_BINDING, });
6.1.4. Texture Destruction
An application that no longer requires a GPUTexture
can choose to lose access to it before
garbage collection by calling destroy().
Note: This allows the user agent to reclaim the GPU
memory associated with the GPUTexture
once
all previously submitted operations using it are complete.
GPUTexture
has the following methods:
destroy()-
Destroys the
GPUTexture.Called on:GPUTexturethis.Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the device timeline.
Device timeline steps:-
Set this.
[[destroyed]]to true.
-
6.2. GPUTextureView
A GPUTextureView
is a view onto some subset of the texture subresources defined by
a particular GPUTexture.
[Exposed =(Window ,Worker ),SecureContext ]interface GPUTextureView { };GPUTextureView includes GPUObjectBase ;
GPUTextureView
has the following immutable properties:
[[texture]], readonly-
The
GPUTextureinto which this is a view. [[descriptor]], readonly-
The
GPUTextureViewDescriptordescribing this texture view.All optional fields of
GPUTextureViewDescriptorare defined. [[renderExtent]], readonly-
For renderable views, this is the effective
GPUExtent3DDictfor rendering.Note: this extent depends on the
baseMipLevel.
[[descriptor]]
desc,
is the subset of the subresources of view.[[texture]]
for which each subresource s satisfies the following:
-
The mipmap level of s is ≥ desc.
baseMipLeveland < desc.baseMipLevel+ desc.mipLevelCount. -
The array layer of s is ≥ desc.
baseArrayLayerand < desc.baseArrayLayer+ desc.arrayLayerCount. -
The aspect of s is in the set of aspects of desc.
aspect.
Two GPUTextureView
objects are texture-view-aliasing if and only if
their sets of subresources intersect.
6.2.1. Texture View Creation
dictionary :GPUTextureViewDescriptor GPUObjectDescriptorBase {GPUTextureFormat format ;GPUTextureViewDimension dimension ;GPUTextureUsageFlags usage = 0;GPUTextureAspect aspect = "all";GPUIntegerCoordinate baseMipLevel = 0;GPUIntegerCoordinate mipLevelCount ;GPUIntegerCoordinate baseArrayLayer = 0;GPUIntegerCoordinate arrayLayerCount ; };
GPUTextureViewDescriptor
has the following members:
format, of type GPUTextureFormat-
The format of the texture view. Must be either the
formatof the texture or one of theviewFormatsspecified during its creation. dimension, of type GPUTextureViewDimension-
The dimension to view the texture as.
usage, of type GPUTextureUsageFlags, defaulting to0-
The allowed
usage(s)for the texture view. Must be a subset of theusageflags of the texture. If 0, defaults to the full set ofusageflags of the texture.Note: If the view’s
formatdoesn’t support all of the texture’susages, the default will fail, and the view’susagemust be specified explicitly. aspect, of type GPUTextureAspect, defaulting to"all"-
Which
aspect(s)of the texture are accessible to the texture view. baseMipLevel, of type GPUIntegerCoordinate, defaulting to0-
The first (most detailed) mipmap level accessible to the texture view.
mipLevelCount, of type GPUIntegerCoordinate-
How many mipmap levels, starting with
baseMipLevel, are accessible to the texture view. baseArrayLayer, of type GPUIntegerCoordinate, defaulting to0-
The index of the first array layer accessible to the texture view.
arrayLayerCount, of type GPUIntegerCoordinate-
How many array layers, starting with
baseArrayLayer, are accessible to the texture view.
enum {GPUTextureViewDimension "1d" ,"2d" ,"2d-array" ,"cube" ,"cube-array" ,"3d" , };
"1d"-
The texture is viewed as a 1-dimensional image.
Corresponding WGSL types:
-
texture_1d -
texture_storage_1d
-
"2d"-
The texture is viewed as a single 2-dimensional image.
Corresponding WGSL types:
-
texture_2d -
texture_storage_2d -
texture_multisampled_2d -
texture_depth_2d -
texture_depth_multisampled_2d
-
"2d-array"-
The texture view is viewed as an array of 2-dimensional images.
Corresponding WGSL types:
-
texture_2d_array -
texture_storage_2d_array -
texture_depth_2d_array
-
"cube"-
The texture is viewed as a cubemap.
The view has 6 array layers, each corresponding to a face of the cube in the order
[+X, -X, +Y, -Y, +Z, -Z]and the following orientations:Cubemap faces. The +U/+V axes indicate the individual faces' texture coordinates, and thus the texel copy memory layout of each face. Note: When viewed from the inside, this results in a left-handed coordinate system where +X is right, +Y is up, and +Z is forward.
Sampling is done seamlessly across the faces of the cubemap.
Corresponding WGSL types:
-
texture_cube -
texture_depth_cube
-
"cube-array"-
The texture is viewed as a packed array of n cubemaps, each with 6 array layers behaving like one
"cube"view, for 6n array layers in total.Corresponding WGSL types:
-
texture_cube_array -
texture_depth_cube_array
-
"3d"-
The texture is viewed as a 3-dimensional image.
Corresponding WGSL types:
-
texture_3d -
texture_storage_3d
-
Each GPUTextureAspect value corresponds to a set of aspects.
The set of aspects are defined for each value below.
enum GPUTextureAspect {"all" ,"stencil-only" ,"depth-only" , };
"all"-
All available aspects of the texture format will be accessible to the texture view. For color formats the color aspect will be accessible. For combined depth-stencil formats both the depth and stencil aspects will be accessible. Depth-or-stencil formats with a single aspect will only make that aspect accessible.
The set of aspects is [color, depth, stencil].
"stencil-only"-
Only the stencil aspect of a depth-or-stencil format format will be accessible to the texture view.
The set of aspects is [stencil].
"depth-only"-
Only the depth aspect of a depth-or-stencil format format will be accessible to the texture view.
The set of aspects is [depth].
createView(descriptor)-
Creates a
GPUTextureView.NOTE:By defaultcreateView()will create a view with a dimension that can represent the entire texture. For example, callingcreateView()without specifying adimensionon a"2d"texture with more than one layer will create a"2d-array"GPUTextureView, even if anarrayLayerCountof 1 is specified.For textures created from sources where the layer count is unknown at the time of development it is recommended that calls to
createView()are provided with an explicitdimensionto ensure shader compatibility.Called on:GPUTexturethis.Arguments:
Arguments for the GPUTexture.createView(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUTextureViewDescriptor✘ ✔ Description of the GPUTextureViewto create.Returns: view, of type
GPUTextureView.Content timeline steps:
-
? Validate texture format required features of descriptor.
formatwith this.[[device]]. -
Let view be ! create a new WebGPU object(this,
GPUTextureView, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return view.
Device timeline initialization steps:-
Set descriptor to the result of resolving GPUTextureViewDescriptor defaults for this with descriptor.
-
If any of the following conditions are unsatisfied generate a validation error, invalidate view and return.
-
this is valid to use with this.
[[device]]. -
If the descriptor.
aspectis"all":-
descriptor.
formatmust equal either this.formator one of the formats in this.[[viewFormats]].
Otherwise:
-
descriptor.
formatmust equal the result of resolving GPUTextureAspect( this.format, descriptor.aspect).
-
-
If descriptor.
usageincludes theRENDER_ATTACHMENTbit:-
descriptor.
formatmust be a renderable format.
-
-
If descriptor.
usageincludes theSTORAGE_BINDINGbit:-
descriptor.
formatmust be listed in § 26.1.1 Plain color formats table withSTORAGE_BINDINGcapability for at least one access mode.
-
-
descriptor.
mipLevelCountmust be > 0. -
descriptor.
baseMipLevel+ descriptor.mipLevelCountmust be ≤ this.mipLevelCount. -
descriptor.
arrayLayerCountmust be > 0. -
descriptor.
baseArrayLayer+ descriptor.arrayLayerCountmust be ≤ the array layer count of this. -
If this.
sampleCount> 1, descriptor.dimensionmust be"2d". -
If descriptor.
dimensionis:"1d"-
-
descriptor.
arrayLayerCountmust be1.
"2d"-
-
descriptor.
arrayLayerCountmust be1.
"2d-array""cube"-
-
descriptor.
arrayLayerCountmust be6.
"cube-array"-
-
descriptor.
arrayLayerCountmust be a multiple of6.
"3d"-
-
descriptor.
arrayLayerCountmust be1.
-
-
Let view be a new
GPUTextureViewobject. -
Set view.
[[texture]]to this. -
Set view.
[[descriptor]]to descriptor. -
If descriptor.
usagecontainsRENDER_ATTACHMENT:-
Let renderExtent be compute render extent([this.
width, this.height, this.depthOrArrayLayers], descriptor.baseMipLevel). -
Set view.
[[renderExtent]]to renderExtent.
-
-
GPUTextureView
texture with a GPUTextureViewDescriptor
descriptor, run the following device timeline steps:
-
Let resolved be a copy of descriptor.
-
If resolved.
mipLevelCountis not provided: set resolved.mipLevelCountto texture.mipLevelCount− resolved.baseMipLevel. -
If resolved.
dimensionis not provided and texture.dimensionis: -
If resolved.
arrayLayerCountis not provided and resolved.dimensionis:"1d","2d", or"3d"-
Set resolved.
arrayLayerCountto1. "cube"-
Set resolved.
arrayLayerCountto6. "2d-array"or"cube-array"-
Set resolved.
arrayLayerCountto the array layer count of texture − resolved.baseArrayLayer.
-
If resolved.
usageis0: set resolved.usageto texture.usage. -
Return resolved.
GPUTexture
texture, run the
following steps:
-
If texture.
dimensionis:"1d"or"3d"-
Return
1. "2d"-
Return texture.
depthOrArrayLayers.
6.3. Texture Formats
The name of the format specifies the order of components, bits per component, and data type for the component.
-
r,g,b,a= red, green, blue, alpha -
unorm= unsigned normalized -
snorm= signed normalized -
uint= unsigned int -
sint= signed int -
float= floating point
If the format has the -srgb suffix, then sRGB conversions from gamma to linear
and vice versa are applied during the reading and writing of color values in the
shader. Compressed texture formats are provided by features. Their naming
should follow the convention here, with the texture name as a prefix. e.g.
etc2-rgba8unorm.
The texel block is a single
addressable element of the textures in pixel-based GPUTextureFormats,
and a single compressed block of the textures in block-based compressed GPUTextureFormats.
The texel block width and texel block height specifies the dimension of one texel block.
-
For pixel-based
GPUTextureFormats, the texel block width and texel block height are always 1. -
For block-based compressed
GPUTextureFormats, the texel block width is the number of texels in each row of one texel block, and the texel block height is the number of texel rows in one texel block. See § 26.1 Texture Format Capabilities for an exhaustive list of values for every texture format.
The texel block
copy footprint of an aspect of a
GPUTextureFormat
is the number of
bytes one texel block occupies during a texel copy, if applicable.
Note:
The texel block
memory cost of a GPUTextureFormat
is the number of
bytes needed to store one texel
block. It is not fully defined for all formats.
This value is informative and non-normative.
enum { // 8-bit formatsGPUTextureFormat ,"r8unorm" ,"r8snorm" ,"r8uint" , // 16-bit formats"r8sint" ,"r16unorm" ,"r16snorm" ,"r16uint" ,"r16sint" ,"r16float" ,"rg8unorm" ,"rg8snorm" ,"rg8uint" , // 32-bit formats"rg8sint" ,"r32uint" ,"r32sint" ,"r32float" ,"rg16unorm" ,"rg16snorm" ,"rg16uint" ,"rg16sint" ,"rg16float" ,"rgba8unorm" ,"rgba8unorm-srgb" ,"rgba8snorm" ,"rgba8uint" ,"rgba8sint" ,"bgra8unorm" , // Packed 32-bit formats"bgra8unorm-srgb" ,"rgb9e5ufloat" ,"rgb10a2uint" ,"rgb10a2unorm" , // 64-bit formats"rg11b10ufloat" ,"rg32uint" ,"rg32sint" ,"rg32float" ,"rgba16unorm" ,"rgba16snorm" ,"rgba16uint" ,"rgba16sint" , // 128-bit formats"rgba16float" ,"rgba32uint" ,"rgba32sint" , // Depth/stencil formats"rgba32float" ,"stencil8" ,"depth16unorm" ,"depth24plus" ,"depth24plus-stencil8" , // "depth32float-stencil8" feature"depth32float" , // BC compressed formats usable if "texture-compression-bc" is both // supported by the device/user agent and enabled in requestDevice."depth32float-stencil8" ,"bc1-rgba-unorm" ,"bc1-rgba-unorm-srgb" ,"bc2-rgba-unorm" ,"bc2-rgba-unorm-srgb" ,"bc3-rgba-unorm" ,"bc3-rgba-unorm-srgb" ,"bc4-r-unorm" ,"bc4-r-snorm" ,"bc5-rg-unorm" ,"bc5-rg-snorm" ,"bc6h-rgb-ufloat" ,"bc6h-rgb-float" ,"bc7-rgba-unorm" , // ETC2 compressed formats usable if "texture-compression-etc2" is both // supported by the device/user agent and enabled in requestDevice."bc7-rgba-unorm-srgb" ,"etc2-rgb8unorm" ,"etc2-rgb8unorm-srgb" ,"etc2-rgb8a1unorm" ,"etc2-rgb8a1unorm-srgb" ,"etc2-rgba8unorm" ,"etc2-rgba8unorm-srgb" ,"eac-r11unorm" ,"eac-r11snorm" ,"eac-rg11unorm" , // ASTC compressed formats usable if "texture-compression-astc" is both // supported by the device/user agent and enabled in requestDevice."eac-rg11snorm" ,"astc-4x4-unorm" ,"astc-4x4-unorm-srgb" ,"astc-5x4-unorm" ,"astc-5x4-unorm-srgb" ,"astc-5x5-unorm" ,"astc-5x5-unorm-srgb" ,"astc-6x5-unorm" ,"astc-6x5-unorm-srgb" ,"astc-6x6-unorm" ,"astc-6x6-unorm-srgb" ,"astc-8x5-unorm" ,"astc-8x5-unorm-srgb" ,"astc-8x6-unorm" ,"astc-8x6-unorm-srgb" ,"astc-8x8-unorm" ,"astc-8x8-unorm-srgb" ,"astc-10x5-unorm" ,"astc-10x5-unorm-srgb" ,"astc-10x6-unorm" ,"astc-10x6-unorm-srgb" ,"astc-10x8-unorm" ,"astc-10x8-unorm-srgb" ,"astc-10x10-unorm" ,"astc-10x10-unorm-srgb" ,"astc-12x10-unorm" ,"astc-12x10-unorm-srgb" ,"astc-12x12-unorm" , };"astc-12x12-unorm-srgb"
The depth component of the "depth24plus"
and "depth24plus-stencil8"
formats may be implemented as either a 24-bit depth value or a "depth32float"
value.
The stencil8
format may be implemented as
either a real "stencil8", or "depth24stencil8", where the depth aspect is
hidden and inaccessible.
-
For 24-bit depth, 1 ULP has a constant value of 1 / (224 − 1).
-
For depth32float, 1 ULP has a variable value no greater than 1 / (224).
A format is renderable if it is either a color renderable format, or a depth-or-stencil format.
If a format is listed in § 26.1.1 Plain color formats with RENDER_ATTACHMENT
capability, it is a
color renderable format. Any other format is not a color renderable format.
All depth-or-stencil formats are renderable.
A renderable format is also blendable if it can be used with render pipeline blending. See § 26.1 Texture Format Capabilities.
A format is filterable if it supports the
GPUTextureSampleType
"float"
(not just "unfilterable-float");
that is, it can be used with "filtering"
GPUSamplers.
See § 26.1 Texture Format Capabilities.
Arguments:
-
GPUTextureFormatformat -
GPUTextureAspectaspect
Returns: GPUTextureFormat
or null
-
If aspect is:
"all"-
Return format.
"depth-only""stencil-only"-
If format is a depth-stencil-format: Return the aspect-specific format of format according to § 26.1.2 Depth-stencil formats or
nullif the aspect is not present in format.
-
Return
null.
Use of some texture formats require a feature to be enabled on the GPUDevice.
Because new
formats can be added to the specification, those enum values may not be known by the implementation.
In order to normalize behavior across implementations, attempting to use a format that requires a
feature will throw an exception if the associated feature is not enabled on the device. This makes
the behavior the same as when the format is unknown to the implementation.
See § 26.1 Texture Format Capabilities for information about which GPUTextureFormats
require features.
GPUTextureFormat
formatwith logical device device, run the following content timeline steps:
-
If format requires a feature and device.
[[features]]does not contain the feature:-
Throw a
TypeError.
-
6.4. GPUExternalTexture
A GPUExternalTexture
is a sampleable 2D texture wrapping an external video frame.
It is an immutable snapshot; its contents may not change over time, either from inside WebGPU
(it is only sampleable) or from outside WebGPU (e.g. due to video frame advancement).
GPUExternalTextures
can be bound into bind groups via the
externalTexture
bind group layout entry member.
Note that member uses several binding slots, as defined there.
GPUExternalTexture
can be implemented without creating a copy of the imported source,
but this depends implementation-defined factors.
Ownership of the underlying representation may either be exclusive or shared with other
owners (such as a video decoder), but this is not visible to the application.
The underlying representation of an external texture is unobservable (except for precise sampling behavior), but typically may include:
-
Up to three 2D planes of data (e.g. RGBA, Y+UV, Y+U+V).
-
Metadata for converting coordinates before reading from those planes (crop and rotation).
-
Metadata for converting values into the specified output color space (matrices, gammas, 3D LUT).
The configuration used internally by an implementation may not be consistent across time, systems, user agents, media sources, or even frames within a single video source. In order to account for many possible representations, the binding conservatively uses the following, for each external texture:
-
three sampled texture bindings (for up to 3 planes),
-
one sampled texture binding for a 3D LUT,
-
one sampler binding to sample the 3D LUT, and
-
one uniform buffer binding for metadata.
[Exposed =(Window ,Worker ),SecureContext ]interface GPUExternalTexture { };GPUExternalTexture includes GPUObjectBase ;
GPUExternalTexture
has the following immutable properties:
[[descriptor]], of typeGPUExternalTextureDescriptor, readonly-
The descriptor with which the texture was created.
GPUExternalTexture
has the following immutable properties:
[[expired]], of typeboolean, initiallyfalse-
Indicates whether the object has expired (can no longer be used).
Note: Unlike
[[destroyed]]slots, which are similar, this can change fromtrueback tofalse.
6.4.1. Importing External Textures
An external texture is created from an external video object
using importExternalTexture().
An external texture created from an HTMLVideoElement
expires (is destroyed) automatically in a
task after it is imported, instead of manually or upon garbage collection like other resources.
When an external texture expires, its [[expired]]
slot changes to true.
An external texture created from a VideoFrame
expires (is destroyed) when, and only when,
the source VideoFrame
is closed,
either explicitly by close(),
or by other means.
Note: As noted in decode(),
authors should call
close()
on output VideoFrames
to avoid decoder stalls.
If an imported VideoFrame
is dropped without being closed, the imported
GPUExternalTexture
object will keep it alive until it is also dropped.
The VideoFrame
cannot be garbage collected until both objects are dropped.
Garbage collection is unpredictable, so this may still stall the video decoder.
Once the GPUExternalTexture
expires, importExternalTexture()
must be called again.
However, the user agent may un-expire and return the same GPUExternalTexture
again, instead of
creating a new one. This will commonly happen unless the execution of the application is scheduled
to match the video’s frame rate (e.g. using requestVideoFrameCallback()).
If the same object is returned again, it will compare equal, and GPUBindGroups,
GPURenderBundles,
etc. referencing the previous object can still be used.
dictionary :GPUExternalTextureDescriptor GPUObjectDescriptorBase {required (HTMLVideoElement or VideoFrame )source ;PredefinedColorSpace colorSpace = "srgb"; };
GPUExternalTextureDescriptor
dictionaries have the following members:
source, of type(HTMLVideoElement or VideoFrame)-
The video source to import the external texture from. Source size is determined as described by the external source dimensions table.
colorSpace, of type PredefinedColorSpace, defaulting to"srgb"-
The color space the image contents of
sourcewill be converted into when reading.
importExternalTexture(descriptor)-
Creates a
GPUExternalTexturewrapping the provided image source.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.importExternalTexture(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUExternalTextureDescriptor✘ ✘ Provides the external image source object (and any creation options). Returns:
GPUExternalTextureContent timeline steps:
-
Let source be descriptor.
source. -
If the current image contents of source are the same as the most recent
importExternalTexture()call with the same descriptor (ignoringlabel), and the user agent chooses to reuse it:-
Let previousResult be the
GPUExternalTexturereturned previously. -
Set previousResult.
[[expired]]tofalse, renewing ownership of the underlying resource. -
Let result be previousResult.
Note: This allows the application to detect duplicate imports and avoid re-creating dependent objects (such as
GPUBindGroups). Implementations still need to be able to handle a single frame being wrapped by multipleGPUExternalTexture, since import metadata likecolorSpacecan change even for the same frame.Otherwise:
-
If source is not origin-clean, throw a
SecurityErrorand return. -
Let usability be ? check the usability of the image argument(source).
-
If usability is not
good:-
Return an invalidated
GPUExternalTexture.
-
Let data be the result of converting the current image contents of source into the color space descriptor.
colorSpacewith unpremultiplied alpha.This may result in values outside of the range [0, 1]. If clamping is desired, it may be performed after sampling.
Note: This is described like a copy, but may be implemented as a reference to read-only underlying data plus appropriate metadata to perform conversion later.
-
Let result be a new
GPUExternalTextureobject wrapping data.
-
-
If source is an
HTMLVideoElement, queue an automatic expiry task with device this and the following steps:-
Set result.
[[expired]]totrue, releasing ownership of the underlying resource.
Note: An
HTMLVideoElementshould be imported in the same task that samples the texture (which should generally be scheduled usingrequestVideoFrameCallbackorrequestAnimationFrame()depending on the application). Otherwise, a texture could get destroyed by these steps before the application is finished using it. -
-
If source is a
VideoFrame, then when source is closed, run the following steps:-
Set result.
[[expired]]totrue.
-
-
Return result.
-
const videoElement= document. createElement( 'video' ); // ... set up videoElement, wait for it to be ready... function frame() { requestAnimationFrame( frame); // Always re-import the video on every animation frame, because the // import is likely to have expired. // The browser may cache and reuse a past frame, and if it does it // may return the same GPUExternalTexture object again. // In this case, old bind groups are still valid. const externalTexture= gpuDevice. importExternalTexture({ source: videoElement}); // ... render using externalTexture... } requestAnimationFrame( frame);
requestVideoFrameCallback is available:
const videoElement= document. createElement( 'video' ); // ... set up videoElement... function frame() { videoElement. requestVideoFrameCallback( frame); // Always re-import, because we know the video frame has advanced const externalTexture= gpuDevice. importExternalTexture({ source: videoElement}); // ... render using externalTexture... } videoElement. requestVideoFrameCallback( frame);
6.5. Sampling External Texture Bindings
The externalTexture
binding point allows binding GPUExternalTexture
objects (from dynamic image sources like videos). It also supports GPUTexture
and GPUTextureView.
Note:
When a GPUTexture
or a GPUTextureView
is bound to an externalTexture
binding, it is like a GPUExternalTexture
with a single RGBA plane and no crop, rotation, or color
conversion.
External textures are represented in WGSL with texture_external and may be read using
textureLoad and textureSampleBaseClampToEdge.
The sampler provided to textureSampleBaseClampToEdge is used to sample the
underlying textures.
When the binding
resource type is a GPUExternalTexture,
the result is in the color space set
by colorSpace.
It is implementation-dependent whether, for any given external texture, the sampler (and filtering)
is applied before or after conversion from underlying values into the specified color space.
Note: If the internal representation is an RGBA plane, sampling behaves as on a regular 2D texture. If there are several underlying planes (e.g. Y+UV), the sampler is used to sample each underlying texture separately, prior to conversion from YUV to the specified color space.
7. Samplers
7.1. GPUSampler
A GPUSampler
encodes transformations and filtering information that can
be used in a shader to interpret texture resource data.
GPUSamplers
are created via createSampler().
[Exposed =(Window ,Worker ),SecureContext ]interface GPUSampler { };GPUSampler includes GPUObjectBase ;
GPUSampler
has the following immutable properties:
[[descriptor]], of typeGPUSamplerDescriptor, readonly-
The
GPUSamplerDescriptorwith which theGPUSamplerwas created. [[isComparison]], of typeboolean, readonly-
Whether the
GPUSampleris used as a comparison sampler. [[isFiltering]], of typeboolean, readonly-
Whether the
GPUSamplerweights multiple samples of a texture.
7.1.1. GPUSamplerDescriptor
A GPUSamplerDescriptor
specifies the options to use to create a GPUSampler.
dictionary :GPUSamplerDescriptor GPUObjectDescriptorBase {GPUAddressMode addressModeU = "clamp-to-edge";GPUAddressMode addressModeV = "clamp-to-edge";GPUAddressMode addressModeW = "clamp-to-edge";GPUFilterMode magFilter = "nearest";GPUFilterMode minFilter = "nearest";GPUMipmapFilterMode mipmapFilter = "nearest";float lodMinClamp = 0;float lodMaxClamp = 32;GPUCompareFunction compare ; [Clamp ]unsigned short maxAnisotropy = 1; };
addressModeU, of type GPUAddressMode, defaulting to"clamp-to-edge"addressModeV, of type GPUAddressMode, defaulting to"clamp-to-edge"addressModeW, of type GPUAddressMode, defaulting to"clamp-to-edge"-
Specifies the
address modesfor the texture width, height, and depth coordinates, respectively. magFilter, of type GPUFilterMode, defaulting to"nearest"-
Specifies the sampling behavior when the sampled area is smaller than or equal to one texel.
minFilter, of type GPUFilterMode, defaulting to"nearest"-
Specifies the sampling behavior when the sampled area is larger than one texel.
mipmapFilter, of type GPUMipmapFilterMode, defaulting to"nearest"-
Specifies behavior for sampling between mipmap levels.
lodMinClamp, of type float, defaulting to0lodMaxClamp, of type float, defaulting to32-
Specifies the minimum and maximum levels of detail, respectively, used internally when sampling a texture.
compare, of type GPUCompareFunction-
When provided the sampler will be a comparison sampler with the specified
GPUCompareFunction.Note: Comparison samplers may use filtering, but the sampling results will be implementation-dependent and may differ from the normal filtering rules.
maxAnisotropy, of type unsigned short, defaulting to1-
Specifies the maximum anisotropy value clamp used by the sampler. Anisotropic filtering is enabled when
maxAnisotropyis > 1 and the implementation supports it.Anisotropic filtering improves the image quality of textures sampled at oblique viewing angles. Higher
maxAnisotropyvalues indicate the maximum ratio of anisotropy supported when filtering.NOTE:Most implementations supportmaxAnisotropyvalues in range between 1 and 16, inclusive. The used value ofmaxAnisotropywill be clamped to the maximum value that the platform supports.The precise filtering behavior is implementation-dependent.
Level of detail (LOD) describes which mip level(s) are selected when sampling a texture. It may be specified explicitly through shader methods like textureSampleLevel or implicitly determined from the texture coordinate derivatives.
Note: See Scale Factor Operation, LOD Operation and Image Level Selection in the Vulkan 1.3 spec for an example of how implicit LODs may be calculated.
GPUAddressMode
describes the behavior of the sampler if the sampled texels extend beyond the
bounds of the sampled texture.
enum {GPUAddressMode "clamp-to-edge" ,"repeat" ,"mirror-repeat" , };
"clamp-to-edge"-
Texture coordinates are clamped between 0.0 and 1.0, inclusive.
"repeat"-
Texture coordinates wrap to the other side of the texture.
"mirror-repeat"-
Texture coordinates wrap to the other side of the texture, but the texture is flipped when the integer part of the coordinate is odd.
GPUFilterMode
and GPUMipmapFilterMode
describe the behavior of the sampler if the sampled
area does not cover exactly one texel.
Note: See Texel Filtering in the Vulkan 1.3 spec for an example of how samplers may determine which texels are sampled from for the various filtering modes.
enum {GPUFilterMode "nearest" ,"linear" , };enum {GPUMipmapFilterMode ,"nearest" , };"linear"
"nearest"-
Return the value of the texel nearest to the texture coordinates.
"linear"-
Select two texels in each dimension and return a linear interpolation between their values.
GPUCompareFunction
specifies the behavior of a comparison sampler. If a comparison sampler is
used in a shader, the depth_ref is compared to the fetched texel value, and the result of this
comparison test is generated (1.0f for pass, or 0.0f for fail).
After comparison, if texture filtering is enabled, the filtering step occurs, so that comparison
results are mixed together resulting in values in the range [0, 1]. Filtering
should behave
as usual, however it may be computed with lower precision or not mix results at all.
enum {GPUCompareFunction "never" ,"less" ,"equal" ,"less-equal" ,"greater" ,"not-equal" ,"greater-equal" ,"always" , };
"never"-
Comparison tests never pass.
"less"-
A provided value passes the comparison test if it is less than the sampled value.
"equal"-
A provided value passes the comparison test if it is equal to the sampled value.
"less-equal"-
A provided value passes the comparison test if it is less than or equal to the sampled value.
"greater"-
A provided value passes the comparison test if it is greater than the sampled value.
"not-equal"-
A provided value passes the comparison test if it is not equal to the sampled value.
"greater-equal"-
A provided value passes the comparison test if it is greater than or equal to the sampled value.
"always"-
Comparison tests always pass.
7.1.2. Sampler Creation
createSampler(descriptor)-
Creates a
GPUSampler.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createSampler(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUSamplerDescriptor✘ ✔ Description of the GPUSamplerto create.Returns:
GPUSamplerContent timeline steps:
-
Let s be ! create a new WebGPU object(this,
GPUSampler, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return s.
Device timeline initialization steps:-
If any of the following conditions are unsatisfied generate a validation error, invalidate s and return.
-
this must not be lost.
-
descriptor.
lodMinClamp≥ 0. -
descriptor.
lodMaxClamp≥ descriptor.lodMinClamp. -
descriptor.
maxAnisotropy≥ 1.Note: Most implementations support
maxAnisotropyvalues in range between 1 and 16, inclusive. The providedmaxAnisotropyvalue will be clamped to the maximum value that the platform supports. -
If descriptor.
maxAnisotropy> 1:-
descriptor.
magFilter, descriptor.minFilter, and descriptor.mipmapFiltermust be"linear".
-
-
-
Set s.
[[descriptor]]to descriptor. -
Set s.
[[isComparison]]tofalseif thecompareattribute of s.[[descriptor]]isnullor undefined. Otherwise, set it totrue. -
Set s.
[[isFiltering]]tofalseif none ofminFilter,magFilter, ormipmapFilterhas the value of"linear". Otherwise, set it totrue.
-
GPUSampler
that does trilinear filtering and repeats texture coordinates:
const sampler= gpuDevice. createSampler({ addressModeU: 'repeat' , addressModeV: 'repeat' , magFilter: 'linear' , minFilter: 'linear' , mipmapFilter: 'linear' , });
8. Resource Binding
8.1. GPUBindGroupLayout
A GPUBindGroupLayout
defines the interface between a set of resources bound in a GPUBindGroup
and their accessibility in shader stages.
[Exposed =(Window ,Worker ),SecureContext ]interface GPUBindGroupLayout { };GPUBindGroupLayout includes GPUObjectBase ;
GPUBindGroupLayout
has the following immutable properties:
[[descriptor]], of typeGPUBindGroupLayoutDescriptor, readonly
8.1.1. Bind Group Layout Creation
A GPUBindGroupLayout
is created via GPUDevice.createBindGroupLayout().
dictionary :GPUBindGroupLayoutDescriptor GPUObjectDescriptorBase {required sequence <GPUBindGroupLayoutEntry >entries ; };
GPUBindGroupLayoutDescriptor
dictionaries have the following members:
entries, of type sequence<GPUBindGroupLayoutEntry>-
A list of entries describing the shader resource bindings for a bind group.
A GPUBindGroupLayoutEntry
describes a single shader resource binding to be included in a GPUBindGroupLayout.
dictionary {GPUBindGroupLayoutEntry required GPUIndex32 binding ;required GPUShaderStageFlags visibility ;GPUBufferBindingLayout buffer ;GPUSamplerBindingLayout sampler ;GPUTextureBindingLayout texture ;GPUStorageTextureBindingLayout storageTexture ;GPUExternalTextureBindingLayout externalTexture ; };
GPUBindGroupLayoutEntry
dictionaries have the following members:
binding, of type GPUIndex32-
A unique identifier for a resource binding within the
GPUBindGroupLayout, corresponding to aGPUBindGroupEntry.bindingand a @binding attribute in theGPUShaderModule. visibility, of type GPUShaderStageFlags-
A bitset of the members of
GPUShaderStage. Each set bit indicates that aGPUBindGroupLayoutEntry’s resource will be accessible from the associated shader stage. buffer, of type GPUBufferBindingLayoutsampler, of type GPUSamplerBindingLayouttexture, of type GPUTextureBindingLayoutstorageTexture, of type GPUStorageTextureBindingLayoutexternalTexture, of type GPUExternalTextureBindingLayout-
Exactly one of these members must be set, indicating the binding type. The contents of the member specify options specific to that type.
The corresponding resource in
createBindGroup()requires the corresponding binding resource type for this binding.
typedef [EnforceRange ]unsigned long ; [GPUShaderStageFlags Exposed =(Window ,Worker ),SecureContext ]namespace {GPUShaderStage const GPUFlagsConstant VERTEX = 0x1;const GPUFlagsConstant FRAGMENT = 0x2;const GPUFlagsConstant COMPUTE = 0x4; };
GPUShaderStage
contains the following flags, which describe which shader stages a
corresponding GPUBindGroupEntry
for this GPUBindGroupLayoutEntry
will be visible to:
VERTEX-
The bind group entry will be accessible to vertex shaders.
FRAGMENT-
The bind group entry will be accessible to fragment shaders.
COMPUTE-
The bind group entry will be accessible to compute shaders.
The binding member of a GPUBindGroupLayoutEntry
is determined by which member of the
GPUBindGroupLayoutEntry
is defined:
buffer,
sampler,
texture,
storageTexture,
or
externalTexture.
Only one may be defined for any given GPUBindGroupLayoutEntry.
Each member has an associated GPUBindingResource
type and each binding type has an
associated internal usage,
given by this table:
| Binding member | Resource type | Binding
type | Binding usage |
|---|---|---|---|
buffer
| GPUBufferBinding(or GPUBuffer
as shorthand)
| "uniform"
| constant |
"storage"
| storage | ||
"read-only-storage"
| storage-read | ||
sampler
| GPUSampler
| "filtering"
| constant |
"non-filtering"
| |||
"comparison"
| |||
texture
| GPUTextureView(or GPUTexture
as shorthand)
| "float"
| constant |
"unfilterable-float"
| |||
"depth"
| |||
"sint"
| |||
"uint"
| |||
storageTexture
| GPUTextureView(or GPUTexture
as shorthand)
| "write-only"
| storage |
"read-write"
| |||
"read-only"
| storage-read | ||
externalTexture
| GPUExternalTextureor GPUTextureView(or GPUTexture
as shorthand)
| constant |
GPUBindGroupLayoutEntry
values entries
exceeds the
binding slot limits of supported limits limits
if the number of slots used toward a limit exceeds the supported value in limits.
Each entry may use multiple slots toward multiple limits.
Device timeline steps:
-
For each entry in entries, if:
- entry.
buffer?.typeis"uniform"and entry.buffer?.hasDynamicOffsetistrue -
Consider 1
maxDynamicUniformBuffersPerPipelineLayoutslot to be used. - entry.
buffer?.typeis"storage"and entry.buffer?.hasDynamicOffsetistrue -
Consider 1
maxDynamicStorageBuffersPerPipelineLayoutslot to be used.
- entry.
-
For each shader stage stage in «
VERTEX,FRAGMENT,COMPUTE»:-
For each entry in entries for which entry.
visibilitycontains stage, if:- entry.
buffer?.typeis"uniform" -
Consider 1
maxUniformBuffersPerShaderStageslot to be used. - entry.
buffer?.typeis"storage"or"read-only-storage" -
Consider 1
maxStorageBuffersPerShaderStageslot to be used. - entry.
sampleris provided -
Consider 1
maxSamplersPerShaderStageslot to be used. - entry.
textureis provided -
Consider 1
maxSampledTexturesPerShaderStageslot to be used. - entry.
storageTextureis provided -
Consider 1
maxStorageTexturesPerShaderStageslot to be used. - entry.
externalTextureis provided -
Consider 4
maxSampledTexturesPerShaderStageslot, 1maxSamplersPerShaderStageslot, and 1maxUniformBuffersPerShaderStageslot to be used.Note: See
GPUExternalTexturefor an explanation of this behavior.
- entry.
-
enum {GPUBufferBindingType ,"uniform" ,"storage" , };"read-only-storage" dictionary {GPUBufferBindingLayout GPUBufferBindingType type = "uniform";boolean hasDynamicOffset =false ;GPUSize64 minBindingSize = 0; };
GPUBufferBindingLayout
dictionaries have the following members:
type, of type GPUBufferBindingType, defaulting to"uniform"-
Indicates the type required for buffers bound to this bindings.
hasDynamicOffset, of type boolean, defaulting tofalse-
Indicates whether this binding requires a dynamic offset.
minBindingSize, of type GPUSize64, defaulting to0-
Indicates the minimum
sizeof a buffer binding used with this bind point.Bindings are always validated against this size in
createBindGroup().If this is not
0, pipeline creation additionally validates that this value ≥ the minimum buffer binding size of the variable.If this is
0, it is ignored by pipeline creation, and instead draw/dispatch commands validate that each binding in theGPUBindGroupsatisfies the minimum buffer binding size of the variable.Note: Similar execution-time validation is theoretically possible for other binding-related fields specified for early validation, like
sampleTypeandformat, which currently can only be validated in pipeline creation. However, such execution-time validation could be costly or unnecessarily complex, so it is available only forminBindingSizewhich is expected to have the most ergonomic impact.
enum {GPUSamplerBindingType ,"filtering" ,"non-filtering" , };"comparison" dictionary {GPUSamplerBindingLayout GPUSamplerBindingType type = "filtering"; };
GPUSamplerBindingLayout
dictionaries have the following members:
type, of type GPUSamplerBindingType, defaulting to"filtering"-
Indicates the required type of a sampler bound to this bindings.
enum {GPUTextureSampleType ,"float" ,"unfilterable-float" ,"depth" ,"sint" , };"uint" dictionary {GPUTextureBindingLayout GPUTextureSampleType sampleType = "float";GPUTextureViewDimension viewDimension = "2d";boolean multisampled =false ; };
GPUTextureBindingLayout
dictionaries have the following members:
sampleType, of type GPUTextureSampleType, defaulting to"float"-
Indicates the type required for texture views bound to this binding.
viewDimension, of type GPUTextureViewDimension, defaulting to"2d"-
Indicates the required
dimensionfor texture views bound to this binding. multisampled, of type boolean, defaulting tofalse-
Indicates whether or not texture views bound to this binding must be multisampled.
enum {GPUStorageTextureAccess ,"write-only" ,"read-only" , };"read-write" dictionary {GPUStorageTextureBindingLayout GPUStorageTextureAccess access = "write-only";required GPUTextureFormat format ;GPUTextureViewDimension viewDimension = "2d"; };
GPUStorageTextureBindingLayout
dictionaries have the following members:
access, of type GPUStorageTextureAccess, defaulting to"write-only"-
The access mode for this binding, indicating readability and writability.
format, of type GPUTextureFormat-
The required
formatof texture views bound to this binding. viewDimension, of type GPUTextureViewDimension, defaulting to"2d"-
Indicates the required
dimensionfor texture views bound to this binding.
dictionary { };GPUExternalTextureBindingLayout
A GPUBindGroupLayout
object has the following device timeline properties:
[[entryMap]], of type ordered map<GPUSize32,GPUBindGroupLayoutEntry>, readonly-
The map of binding indices pointing to the
GPUBindGroupLayoutEntrys, which thisGPUBindGroupLayoutdescribes. [[dynamicOffsetCount]], of typeGPUSize32, readonly-
The number of buffer bindings with dynamic offsets in this
GPUBindGroupLayout. [[exclusivePipeline]], of typeGPUPipelineBase?, readonly-
The pipeline that created this
GPUBindGroupLayout, if it was created as part of a default pipeline layout. If notnull,GPUBindGroups created with thisGPUBindGroupLayoutcan only be used with the specifiedGPUPipelineBase.
createBindGroupLayout(descriptor)-
Creates a
GPUBindGroupLayout.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createBindGroupLayout(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUBindGroupLayoutDescriptor✘ ✘ Description of the GPUBindGroupLayoutto create.Returns:
GPUBindGroupLayoutContent timeline steps:
-
For each
GPUBindGroupLayoutEntryentry in descriptor.entries:-
If entry.
storageTextureis provided:-
? Validate texture format required features for entry.
storageTexture.formatwith this.[[device]].
-
-
-
Let layout be ! create a new WebGPU object(this,
GPUBindGroupLayout, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return layout.
Device timeline initialization steps:-
If any of the following conditions are unsatisfied generate a validation error, invalidate layout and return.
-
this must not be lost.
-
Let limits be this.
[[device]].[[limits]]. -
The
bindingof each entry in descriptor is unique. -
The
bindingof each entry in descriptor must be < limits.maxBindingsPerBindGroup. -
descriptor.
entriesmust not exceed the binding slot limits of limits. -
For each
GPUBindGroupLayoutEntryentry in descriptor.entries:-
Exactly one of entry.
buffer, entry.sampler, entry.texture, entry.storageTexture, and entry.externalTextureis provided. -
entry.
visibilitycontains only bits defined inGPUShaderStage. -
If entry.
visibilityincludesVERTEX:-
If entry.
bufferis provided, entry.buffer.typemust be"uniform"or"read-only-storage". -
If entry.
storageTextureis provided, entry.storageTexture.accessmust be"read-only".
-
-
If entry.
texture?.multisampledistrue:-
entry.
texture.viewDimensionis"2d". -
entry.
texture.sampleTypeis not"float".
-
-
If entry.
storageTextureis provided:-
entry.
storageTexture.viewDimensionis not"cube"or"cube-array". -
entry.
storageTexture.formatmust be a format which can support storage usage for the given entry.storageTexture.accessaccording to the § 26.1.1 Plain color formats table.
-
-
-
-
Set layout.
[[descriptor]]to descriptor. -
Set layout.
[[dynamicOffsetCount]]to the number of entries in descriptor wherebufferis provided andbuffer.hasDynamicOffsetistrue. -
Set layout.
[[exclusivePipeline]]tonull. -
For each
GPUBindGroupLayoutEntryentry in descriptor.entries:-
Insert entry into layout.
[[entryMap]]with the key of entry.binding.
-
-
8.1.2. Compatibility
GPUBindGroupLayout
objects a and b are considered group-equivalent
if and only if all of the following conditions are satisfied:
-
for any binding number binding, one of the following conditions is satisfied:
-
it’s missing from both a.
[[entryMap]]and b.[[entryMap]]. -
a.
[[entryMap]][binding] == b.[[entryMap]][binding]
-
If bind groups layouts are group-equivalent they can be interchangeably used in all contents.
8.2. GPUBindGroup
A GPUBindGroup
defines a set of resources to be bound together in a group
and how the resources are used in shader stages.
[Exposed =(Window ,Worker ),SecureContext ]interface GPUBindGroup { };GPUBindGroup includes GPUObjectBase ;
GPUBindGroup
has the following device timeline properties:
[[layout]], of typeGPUBindGroupLayout, readonly-
The
GPUBindGroupLayoutassociated with thisGPUBindGroup. [[entries]], of type sequence<GPUBindGroupEntry>, readonly-
The set of
GPUBindGroupEntrys thisGPUBindGroupdescribes. [[usedResources]], of type usage scope, readonly-
The set of buffer and texture subresources used by this bind group, associated with lists of the internal usage flags.
GPUBindGroup
bindGroup,
given list<GPUBufferDynamicOffset> dynamicOffsets, are computed as
follows:
-
Let result be a new set<(
GPUBindGroupLayoutEntry,GPUBufferBinding)>. -
Let dynamicOffsetIndex be 0.
-
For each
GPUBindGroupEntrybindGroupEntry in bindGroup.[[entries]], sorted by bindGroupEntry.binding:-
Let bindGroupLayoutEntry be bindGroup.
[[layout]].[[entryMap]][bindGroupEntry.binding]. -
Let bound be get as buffer binding(bindGroupEntry.
resource). -
If bindGroupLayoutEntry.
buffer.hasDynamicOffset:-
Increment bound.
offsetby dynamicOffsets[dynamicOffsetIndex]. -
Increment dynamicOffsetIndex by 1.
-
-
Append (bindGroupLayoutEntry, bound) to result.
-
-
Return result.
8.2.1. Bind Group Creation
A GPUBindGroup
is created via GPUDevice.createBindGroup().
dictionary :GPUBindGroupDescriptor GPUObjectDescriptorBase {required GPUBindGroupLayout layout ;required sequence <GPUBindGroupEntry >entries ; };
GPUBindGroupDescriptor
dictionaries have the following members:
layout, of type GPUBindGroupLayout-
The
GPUBindGroupLayoutthe entries of this bind group will conform to. entries, of type sequence<GPUBindGroupEntry>-
A list of entries describing the resources to expose to the shader for each binding described by the
layout.
typedef (GPUSampler or GPUTexture or GPUTextureView or GPUBuffer or GPUBufferBinding or GPUExternalTexture );GPUBindingResource dictionary {GPUBindGroupEntry required GPUIndex32 binding ;required GPUBindingResource resource ; };
A GPUBindGroupEntry
describes a single resource to be bound in a GPUBindGroup,
and has the
following members:
binding, of type GPUIndex32-
A unique identifier for a resource binding within the
GPUBindGroup, corresponding to aGPUBindGroupLayoutEntry.bindingand a @binding attribute in theGPUShaderModule. resource, of type GPUBindingResource-
The resource to bind, which may be a
GPUSampler,GPUTexture,GPUTextureView,GPUBuffer,GPUBufferBinding, orGPUExternalTexture.
GPUBindGroupEntry
has the following device timeline properties:
[[prevalidatedSize]], of typeboolean-
Whether or not this binding entry had its buffer size validated at time of creation.
dictionary {GPUBufferBinding required GPUBuffer buffer ;GPUSize64 offset = 0;GPUSize64 size ; };
A GPUBufferBinding
describes a buffer and optional range to bind as a resource, and has the
following members:
buffer, of type GPUBuffer-
The
GPUBufferto bind. offset, of type GPUSize64, defaulting to0-
The offset, in bytes, from the beginning of
bufferto the beginning of the range exposed to the shader by the buffer binding. size, of type GPUSize64-
The size, in bytes, of the buffer binding. If not provided, specifies the range starting at
offsetand ending at the end ofbuffer.
createBindGroup(descriptor)-
Creates a
GPUBindGroup.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createBindGroup(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUBindGroupDescriptor✘ ✘ Description of the GPUBindGroupto create.Returns:
GPUBindGroupContent timeline steps:
-
Let bindGroup be ! create a new WebGPU object(this,
GPUBindGroup, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return bindGroup.
Device timeline initialization steps:-
Let limits be this.
[[device]].[[limits]]. -
If any of the following conditions are unsatisfied generate a validation error, invalidate bindGroup and return.
-
descriptor.
layoutis valid to use with this. -
The number of
entriesof descriptor.layoutis exactly equal to the number of descriptor.entries.
For each
GPUBindGroupEntrybindingDescriptor in descriptor.entries:-
Let resource be bindingDescriptor.
resource. -
There is exactly one
GPUBindGroupLayoutEntrylayoutBinding in descriptor.layout.entriessuch that layoutBinding.bindingequals to bindingDescriptor.binding. -
If the defined binding member for layoutBinding is:
sampler-
-
resource is a
GPUSampler. -
resource is valid to use with this.
-
If layoutBinding.
sampler.typeis:"filtering"-
resource.
[[isComparison]]isfalse. "non-filtering"-
resource.
[[isFiltering]]isfalse. resource.[[isComparison]]isfalse. "comparison"-
resource.
[[isComparison]]istrue.
-
texture-
-
resource is either a
GPUTextureor aGPUTextureView. -
resource is valid to use with this.
-
Let textureView be get as texture view(resource).
-
Let texture be textureView.
[[texture]]. -
layoutBinding.
texture.viewDimensionis equal to textureView’sdimension. -
layoutBinding.
texture.sampleTypeis compatible with textureView’sformat. -
textureView.
[[descriptor]].usageincludesTEXTURE_BINDING. -
If layoutBinding.
texture.multisampledistrue, texture’ssampleCount>1, Otherwise texture’ssampleCountis1.
-
storageTexture-
-
resource is either a
GPUTextureor aGPUTextureView. -
resource is valid to use with this.
-
Let storageTextureView be get as texture view(resource).
-
Let texture be storageTextureView.
[[texture]]. -
layoutBinding.
storageTexture.viewDimensionis equal to storageTextureView’sdimension. -
layoutBinding.
storageTexture.formatis equal to storageTextureView.[[descriptor]].format. -
storageTextureView.
[[descriptor]].usageincludesSTORAGE_BINDING. -
storageTextureView.
[[descriptor]].mipLevelCountmust be 1.
-
buffer-
-
resource is either a
GPUBufferor aGPUBufferBinding. -
Let bufferBinding be get as buffer binding(resource).
-
bufferBinding.
bufferis valid to use with this. -
The bound part designated by bufferBinding.
offsetand bufferBinding.sizeresides inside the buffer and has non-zero size. -
effective buffer binding size(bufferBinding) ≥ layoutBinding.
buffer.minBindingSize. -
If layoutBinding.
buffer.typeis"uniform"-
-
effective buffer binding size(bufferBinding) ≤ limits.
maxUniformBufferBindingSize. -
bufferBinding.
offsetis a multiple of limits.minUniformBufferOffsetAlignment.
"storage"or"read-only-storage"-
-
effective buffer binding size(bufferBinding) ≤ limits.
maxStorageBufferBindingSize. -
effective buffer binding size(bufferBinding) is a multiple of 4.
-
bufferBinding.
offsetis a multiple of limits.minStorageBufferOffsetAlignment.
-
externalTexture-
-
resource is either a
GPUExternalTexture, aGPUTexture, or aGPUTextureView. -
resource is valid to use with this.
-
If resource is a:
GPUTextureorGPUTextureView-
-
Let view be get as texture view(resource).
-
view.
[[descriptor]].usagemust includeTEXTURE_BINDING. -
view.
[[descriptor]].dimensionmust be"2d". -
view.
[[descriptor]].mipLevelCountmust be 1. -
view.
[[descriptor]].formatmust be"rgba8unorm","bgra8unorm", or"rgba16float". -
view.
[[texture]].sampleCountmust be 1.
-
-
-
-
Let bindGroup.
[[layout]]= descriptor.layout. -
Let bindGroup.
[[entries]]= descriptor.entries. -
Let bindGroup.
[[usedResources]]= {}. -
For each
GPUBindGroupEntrybindingDescriptor in descriptor.entries:-
Let internalUsage be the binding usage for layoutBinding.
-
Each subresource seen by resource is added to
[[usedResources]]as internalUsage. -
Let bindingDescriptor.
[[prevalidatedSize]]befalseif the defined binding member for layoutBinding isbufferand layoutBinding.buffer.minBindingSizeis0, andtrueotherwise.
-
-
Arguments:
-
GPUBindingResourceresource
Returns: GPUTextureView
-
Assert resource is either a
GPUTextureor aGPUTextureView. -
If resource is a:
GPUTexture-
-
Return resource.
createView().
-
GPUTextureView-
-
Return resource.
-
Arguments:
-
GPUBindingResourceresource
Returns: GPUBufferBinding
-
Assert resource is either a
GPUBufferor aGPUBufferBinding. -
If resource is a:
GPUBuffer-
-
Let bufferBinding a new
GPUBufferBinding. -
Set bufferBinding.
bufferto resource. -
Return bufferBinding.
-
GPUBufferBinding-
-
Return resource.
-
GPUBufferBinding
objects a and b are considered buffer-binding-aliasing if and only if all of the
following are true:
-
The range formed by a.
offsetand a.sizeintersects the range formed by b.offsetand b.size, where if asizeis unspecified, the range goes to the end of the buffer.
Note: When doing this calculation, any dynamic offsets have already been applied to the ranges.
8.3. GPUPipelineLayout
A GPUPipelineLayout
defines the mapping between resources of all GPUBindGroup
objects set up during command encoding in setBindGroup(), and the shaders of the pipeline
set by GPURenderCommandsMixin.setPipeline
or GPUComputePassEncoder.setPipeline.
The full binding address of a resource can be defined as a trio of:
-
shader stage mask, to which the resource is visible
-
bind group index
-
binding number
The components of this address can also be seen as the binding space of a pipeline. A GPUBindGroup
(with the corresponding GPUBindGroupLayout)
covers that space for a fixed bind group index. The contained bindings need to be a superset of the
resources used by the shader at this bind group index.
[Exposed =(Window ,Worker ),SecureContext ]interface GPUPipelineLayout { };GPUPipelineLayout includes GPUObjectBase ;
GPUPipelineLayout
has the following device timeline properties:
[[bindGroupLayouts]], of type list<GPUBindGroupLayout>, readonly-
The
GPUBindGroupLayoutobjects provided at creation inGPUPipelineLayoutDescriptor.bindGroupLayouts.
Note: using the same GPUPipelineLayout
for many GPURenderPipeline
or GPUComputePipeline
pipelines guarantees that the user agent doesn’t need to rebind any resources internally when there is a
switch between these pipelines.
GPUComputePipeline
object X was created with GPUPipelineLayout.bindGroupLayouts
A, B, C. GPUComputePipeline
object Y was created with GPUPipelineLayout.bindGroupLayouts
A, D, C. Supposing the command encoding sequence has two dispatches:
-
setBindGroup(0, ...)
-
setBindGroup(1, ...)
-
setBindGroup(2, ...)
-
setPipeline(X) -
setBindGroup(1, ...)
-
setPipeline(Y)
In this scenario, the user agent would have to re-bind the group slot 2 for the second dispatch, even
though neither the GPUBindGroupLayout
at index 2 of GPUPipelineLayout.bindGroupLayouts,
or the GPUBindGroup
at slot 2, change.
Note: the expected usage of the GPUPipelineLayout
is placing the most common and the least frequently changing bind groups at the "bottom" of the layout,
meaning lower bind group slot numbers, like 0 or 1. The more frequently a bind group needs to change between
draw calls, the higher its index should be. This general guideline allows the user agent to minimize state
changes between draw calls, and consequently lower the CPU overhead.
8.3.1. Pipeline Layout Creation
A GPUPipelineLayout
is created via GPUDevice.createPipelineLayout().
dictionary :GPUPipelineLayoutDescriptor GPUObjectDescriptorBase {required sequence <GPUBindGroupLayout ?>bindGroupLayouts ; };
GPUPipelineLayoutDescriptor
dictionaries define all the GPUBindGroupLayouts
used by a
pipeline, and have the following members:
bindGroupLayouts, of typesequence<GPUBindGroupLayout?>-
A list of optional
GPUBindGroupLayouts the pipeline will use. Each element corresponds to a @group attribute in theGPUShaderModule, with theNth element corresponding with@group(N).
createPipelineLayout(descriptor)-
Creates a
GPUPipelineLayout.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createPipelineLayout(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUPipelineLayoutDescriptor✘ ✘ Description of the GPUPipelineLayoutto create.Returns:
GPUPipelineLayoutContent timeline steps:
-
Let pl be ! create a new WebGPU object(this,
GPUPipelineLayout, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return pl.
Device timeline initialization steps:-
Let limits be this.
[[device]].[[limits]]. -
Let bindGroupLayouts be a list of
nullGPUBindGroupLayouts with size equal to limits.maxBindGroups. -
For each bindGroupLayout at index i in descriptor.
bindGroupLayouts:-
If bindGroupLayout is not
nulland bindGroupLayout.[[descriptor]].entriesis not empty:-
Set bindGroupLayouts[i] to bindGroupLayout.
-
-
-
Let allEntries be the result of concatenating bgl.
[[descriptor]].entriesfor all non-nullbgl in bindGroupLayouts. -
If any of the following conditions are unsatisfied generate a validation error, invalidate pl and return.
-
Every non-
nullGPUBindGroupLayoutin bindGroupLayouts must be valid to use with this and have a[[exclusivePipeline]]ofnull. -
The size of descriptor.
bindGroupLayoutsmust be ≤ limits.maxBindGroups. -
allEntries must not exceed the binding slot limits of limits.
-
-
Set the pl.
[[bindGroupLayouts]]to bindGroupLayouts.
-
Note: two GPUPipelineLayout
objects are considered equivalent for any usage
if their internal [[bindGroupLayouts]]
sequences contain
GPUBindGroupLayout
objects that are group-equivalent.
8.4. Example
GPUBindGroupLayout
that describes a binding with a uniform buffer, a texture, and a sampler.
Then create a GPUBindGroup
and a GPUPipelineLayout
using the GPUBindGroupLayout.
const bindGroupLayout= gpuDevice. createBindGroupLayout({ entries: [{ binding: 0 , visibility: GPUShaderStage. VERTEX| GPUShaderStage. FRAGMENT, buffer: {} }, { binding: 1 , visibility: GPUShaderStage. FRAGMENT, texture: {} }, { binding: 2 , visibility: GPUShaderStage. FRAGMENT, sampler: {} }] }); const bindGroup= gpuDevice. createBindGroup({ layout: bindGroupLayout, entries: [{ binding: 0 , resource: { buffer: buffer}, }, { binding: 1 , resource: texture}, { binding: 2 , resource: sampler}] }); const pipelineLayout= gpuDevice. createPipelineLayout({ bindGroupLayouts: [ bindGroupLayout] });
9. Shader Modules
9.1. GPUShaderModule
[Exposed =(Window ,Worker ),SecureContext ]interface GPUShaderModule {Promise <GPUCompilationInfo >getCompilationInfo (); };GPUShaderModule includes GPUObjectBase ;
GPUShaderModule
is a reference to an internal shader module object.
9.1.1. Shader Module Creation
dictionary :GPUShaderModuleDescriptor GPUObjectDescriptorBase {required USVString code ;sequence <GPUShaderModuleCompilationHint >compilationHints = []; };
code, of type USVString-
The WGSL source code for the shader module.
compilationHints, of type sequence<GPUShaderModuleCompilationHint>, defaulting to[]-
A list of
GPUShaderModuleCompilationHints.Any hint provided by an application should contain information about one entry point of a pipeline that will eventually be created from the entry point.
Implementations should use any information present in the
GPUShaderModuleCompilationHintto perform as much compilation as is possible withincreateShaderModule().Aside from type-checking, these hints are not validated in any way.
NOTE:Supplying information incompilationHintsdoes not have any observable effect, other than performance. It may be detrimental to performance to provide hints for pipelines that never end up being created.Because a single shader module can hold multiple entry points, and multiple pipelines can be created from a single shader module, it can be more performant for an implementation to do as much compilation as possible once in
createShaderModule()rather than multiple times in the multiple calls tocreateComputePipeline()orcreateRenderPipeline().Hints are only applied to the entry points they explicitly name. Unlike
GPUProgrammableStage.entryPoint, there is no default, even if only one entry point is present in the module.Note: Hints are not validated in an observable way, but user agents may surface identifiable errors (like unknown entry point names or incompatible pipeline layouts) to developers, for example in the browser developer console.
createShaderModule(descriptor)-
Creates a
GPUShaderModule.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createShaderModule(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUShaderModuleDescriptor✘ ✘ Description of the GPUShaderModuleto create.Returns:
GPUShaderModuleContent timeline steps:
-
Let sm be ! create a new WebGPU object(this,
GPUShaderModule, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return sm.
Device timeline initialization steps:-
Let error be any error that results from shader module creation with the WGSL source descriptor.
code, ornullif no errors occured. -
If any of the following requirements are unmet, generate a validation error, invalidate sm, and return.
-
this must not be lost.
-
error must not be a shader-creation program error.
-
For each
enableextension in descriptor.code, the correspondingGPUFeatureNamemust be enabled (see the Feature Index).
Note: Uncategorized errors cannot arise from shader module creation. Implementations which detect such errors during shader module creation must behave as if the shader module is valid, and defer surfacing the error until pipeline creation.
-
NOTE:User agents should not include detailed compiler error messages or shader text in themessagetext of validation errors arising here: these details are accessible viagetCompilationInfo(). User agents should surface human-readable, formatted error details to developers for easier debugging (for example as a warning in the browser developer console, expandable to show full shader source).As shader compilation errors should be rare in production applications, user agents could choose to surface them to developers regardless of error handling (GPU error scopes or
uncapturederrorevent handlers), e.g. as an expandable warning. If not, they should provide and document another way for developers to access human-readable error details, for example by adding a checkbox to show errors unconditionally, or by showing human-readable details when logging aGPUCompilationInfoobject to the console. -
GPUShaderModule
from WGSL code:
// A simple vertex and fragment shader pair that will fill the viewport with red. const shaderSource= ` var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>( vec2(-1.0, -1.0), vec2(-1.0, 3.0), vec2(3.0, -1.0)); @vertex fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> @builtin(position) vec4<f32> { return vec4(pos[vertexIndex], 1.0, 1.0); } @fragment fn fragmentMain() -> @location(0) vec4<f32> { return vec4(1.0, 0.0, 0.0, 1.0); } ` ; const shaderModule= gpuDevice. createShaderModule({ code: shaderSource, });
9.1.1.1. Shader Module Compilation Hints
Shader module compilation hints are optional, additional information indicating how a given
GPUShaderModule
entry point is intended to be used in the future. For some implementations this
information may aid in compiling the shader module earlier, potentially increasing performance.
dictionary {GPUShaderModuleCompilationHint required USVString ; (entryPoint GPUPipelineLayout or GPUAutoLayoutMode )layout ; };
layout, of type(GPUPipelineLayout or GPUAutoLayoutMode)-
A
GPUPipelineLayoutthat theGPUShaderModulemay be used with in a futurecreateComputePipeline()orcreateRenderPipeline()call. If set to"auto"the layout will be the default pipeline layout for the entry point associated with this hint will be used.
createShaderModule()
and createComputePipeline()
/
createRenderPipeline().
If an application is unable to provide hint information at the time of calling
createShaderModule(),
it should usually not delay calling
createShaderModule(),
but instead just omit the unknown information from
the compilationHints
sequence or the individual members of
GPUShaderModuleCompilationHint.
Omitting this information
may cause compilation to be deferred to createComputePipeline()
/
createRenderPipeline().
If an author is not confident that the hint information passed to createShaderModule()
will match the information later passed to createComputePipeline()
/
createRenderPipeline()
with that same module, they should avoid passing that
information to createShaderModule(),
as passing mismatched information to
createShaderModule()
may cause unnecessary compilations to occur.
9.1.2. Shader Module Compilation Information
enum {GPUCompilationMessageType ,"error" ,"warning" , }; ["info" Exposed =(Window ,Worker ),Serializable ,SecureContext ]interface {GPUCompilationMessage readonly attribute DOMString message ;readonly attribute GPUCompilationMessageType type ;readonly attribute unsigned long long lineNum ;readonly attribute unsigned long long linePos ;readonly attribute unsigned long long offset ;readonly attribute unsigned long long length ; }; [Exposed =(Window ,Worker ),Serializable ,SecureContext ]interface {GPUCompilationInfo readonly attribute FrozenArray <GPUCompilationMessage >; };messages
A GPUCompilationMessage
is an informational, warning, or error message generated by the
GPUShaderModule
compiler. The messages are intended to be human readable to help developers
diagnose issues with their shader code.
Each message may correspond to
either a single point in the shader code, a substring of the shader code, or may not correspond to
any specific point in the code at all.
GPUCompilationMessage
has the following attributes:
message, of type DOMString, readonly-
The human-readable, localizable text for this compilation message.
Note: The
messageshould follow the best practices for language and direction information. This includes making use of any future standards which may emerge regarding the reporting of string language and direction metadata.Editorial note: At the time of this writing, no language/direction recommendation is available that provides compatibility and consistency with legacy APIs, but when there is, adopt it formally.
type, of type GPUCompilationMessageType, readonly-
The severity level of the message.
If the
typeis"error", it corresponds to a shader-creation error. lineNum, of type unsigned long long, readonly-
The line number in the shader
codethemessagecorresponds to. Value is one-based, such that a lineNum of1indicates the first line of the shadercode. Lines are delimited by line breaks.If the
messagecorresponds to a substring this points to the line on which the substring begins. Must be0if themessagedoes not correspond to any specific point in the shadercode. linePos, of type unsigned long long, readonly-
The offset, in UTF-16 code units, from the beginning of line
lineNumof the shadercodeto the point or beginning of the substring that themessagecorresponds to. Value is one-based, such that alinePosof1indicates the first code unit of the line.If
messagecorresponds to a substring this points to the first UTF-16 code unit of the substring. Must be0if themessagedoes not correspond to any specific point in the shadercode. offset, of type unsigned long long, readonly-
The offset from the beginning of the shader
codein UTF-16 code units to the point or beginning of the substring thatmessagecorresponds to. Must reference the same position aslineNumandlinePos. Must be0if themessagedoes not correspond to any specific point in the shadercode. length, of type unsigned long long, readonly-
The number of UTF-16 code units in the substring that
messagecorresponds to. If the message does not correspond with a substring thenlengthmust be 0.
Note: GPUCompilationMessage.lineNum
and
GPUCompilationMessage.linePos
are one-based since the most common use
for them is expected to be printing human readable messages that can be correlated with the line and
column numbers shown in many text editors.
Note: GPUCompilationMessage.offset
and
GPUCompilationMessage.length
are appropriate to pass to
substr() in order to retrieve the substring of the shader code
the
message
corresponds to.
getCompilationInfo()-
Returns any messages generated during the
GPUShaderModule’s compilation.The locations, order, and contents of messages are implementation-defined In particular, messages may not be ordered by
lineNum.Called on:GPUShaderModulethisReturns:
Promise<GPUCompilationInfo>Content timeline steps:
-
Let contentTimeline be the current Content timeline.
-
Let promise be a new promise.
-
Issue the synchronization steps on the Device timeline of this.
-
Return promise.
Device timeline synchronization steps:-
Let event occur upon the (successful or unsuccessful) completion of shader module creation for this.
-
Listen for timeline event event on this.
[[device]], handled by the subsequent steps on contentTimeline.
Content timeline steps:-
Let info be a new
GPUCompilationInfo. -
Let messages be a list of any errors, warnings, or informational messages generated during shader module creation for this, or the empty list
[]if the device was lost. -
For each message in messages:
-
Let m be a new
GPUCompilationMessage. -
Set m.
messageto be the text of message. -
- If message is associated with a specific substring or
position
within the shader
code: -
-
Set m.
lineNumto the one-based number of the first line that the message refers to. -
Set m.
linePosto the one-based number of the first UTF-16 code units on m.lineNumthat the message refers to, or1if the message refers to the entire line. -
Set m.
offsetto the number of UTF-16 code units from the beginning of the shader to beginning of the substring or position that message refers to. -
Set m.
lengththe length of the substring in UTF-16 code units that message refers to, or 0 if message refers to a position
-
- Otherwise:
- If message is associated with a specific substring or
position
within the shader
-
-
Resolve promise with info.
-
10. Pipelines
A pipeline, be it GPUComputePipeline
or GPURenderPipeline,
represents the complete function done by a combination of the GPU hardware, the driver,
and the user agent, that process the input data in the shape of bindings and vertex buffers,
and produces some output, like the colors in the output render targets.
Structurally, the pipeline consists of a sequence of programmable stages (shaders) and fixed-function states, such as the blending modes.
Note: Internally, depending on the target platform, the driver may convert some of the fixed-function states into shader code, and link it together with the shaders provided by the user. This linking is one of the reason the object is created as a whole.
This combination state is created as a single object
(a GPUComputePipeline
or GPURenderPipeline)
and switched using one command
(GPUComputePassEncoder.setPipeline()
or
GPURenderCommandsMixin.setPipeline()
respectively).
There are two ways to create pipelines:
- immediate pipeline creation
-
createComputePipeline()andcreateRenderPipeline()return a pipeline object which can be used immediately in a pass encoder.When this fails, the pipeline object will be invalid and the call will generate either a validation error or an internal error.
Note: A handle object is returned immediately, but actual pipeline creation is not synchronous. If pipeline creation takes a long time, this can incur a stall in the device timeline at some point between the creation call and execution of the
submit()in which it is first used. The point is unspecified, but most likely to be one of: at creation, at the first usage of the pipeline insetPipeline(), at the correspondingfinish()of thatGPUCommandEncoderorGPURenderBundleEncoder, or atsubmit()of thatGPUCommandBuffer. - async pipeline creation
-
createComputePipelineAsync()andcreateRenderPipelineAsync()return aPromisewhich resolves to a pipeline object when creation of the pipeline has completed.When this fails, the
Promiserejects with aGPUPipelineError.
GPUPipelineError describes a pipeline creation failure.
[Exposed =(Window ,Worker ),SecureContext ,Serializable ]interface GPUPipelineError :DOMException {constructor (optional DOMString message = "",GPUPipelineErrorInit options );readonly attribute GPUPipelineErrorReason reason ; };dictionary {GPUPipelineErrorInit required GPUPipelineErrorReason ; };reason enum GPUPipelineErrorReason {"validation" ,"internal" , };
GPUPipelineError
constructor:
constructor()-
Arguments:
Arguments for the GPUPipelineError.constructor() method. Parameter Type Nullable Optional Description messageDOMString✘ ✔ Error message of the base DOMException.optionsGPUPipelineErrorInit✘ ✘ Options specific to GPUPipelineError.Content timeline steps:
GPUPipelineError
has the following attributes:
reason, of type GPUPipelineErrorReason, readonly-
A read-only slot-backed attribute exposing the type of error encountered in pipeline creation as a
GPUPipelineErrorReason:-
"validation": A validation error. -
"internal": An internal error.
-
GPUPipelineError
objects are serializable
objects.
-
Run the
DOMExceptionserialization steps given value and serialized.
-
Run the
DOMExceptiondeserialization steps given value and serialized.
10.1. Base pipelines
enum {GPUAutoLayoutMode , };"auto" dictionary :GPUPipelineDescriptorBase GPUObjectDescriptorBase {required (GPUPipelineLayout or GPUAutoLayoutMode )layout ; };
layout, of type(GPUPipelineLayout or GPUAutoLayoutMode)-
The
GPUPipelineLayoutfor this pipeline, or"auto"to generate the pipeline layout automatically.Note: If
"auto"is used the pipeline cannot shareGPUBindGroups with any other pipelines.
interface mixin { [GPUPipelineBase NewObject ]GPUBindGroupLayout getBindGroupLayout (unsigned long index ); };
GPUPipelineBase
has the following device timeline properties:
[[layout]], of typeGPUPipelineLayout-
The definition of the layout of resources which can be used with
this.
GPUPipelineBase
has the following methods:
getBindGroupLayout(index)-
Gets a
GPUBindGroupLayoutthat is compatible with theGPUPipelineBase’sGPUBindGroupLayoutatindex.Called on:GPUPipelineBasethisArguments:
Arguments for the GPUPipelineBase.getBindGroupLayout(index) method. Parameter Type Nullable Optional Description indexunsigned long✘ ✘ Index into the pipeline layout’s [[bindGroupLayouts]]sequence.Returns:
GPUBindGroupLayoutContent timeline steps:
-
Let layout be a new
GPUBindGroupLayoutobject. -
Issue the initialization steps on the Device timeline of this.
-
Return layout.
Device timeline initialization steps:-
Let limits be this.
[[device]].[[limits]]. -
If any of the following conditions are unsatisfied generate a validation error, invalidate layout and return.
-
this must be valid.
-
index < limits.
maxBindGroups.
-
-
Initialize layout so it is a copy of this.
[[layout]].[[bindGroupLayouts]][index].Note:
GPUBindGroupLayoutis only ever used by-value, not by-reference, so this is equivalent to returning the same internal object with a new WebGPU interface. A newGPUBindGroupLayoutWebGPU interface is returned each time to avoid a round-trip between the Content timeline and the Device timeline.
-
10.1.1. Default pipeline layout
A GPUPipelineBase
object that was created with a layout
set to
"auto"
has a default layout created and used instead.
Note: Default layouts are provided as a convenience for simple pipelines, but use of explicit layouts is recommended in most cases. Bind groups created from default layouts cannot be used with other pipelines, and the structure of the default layout may change when altering shaders, causing unexpected bind group creation errors.
To create a default pipeline layout for GPUPipelineBase
pipeline,
run the following device
timeline steps:
-
Let groupCount be 0.
-
Let groupDescs be a sequence of device.
[[limits]].maxBindGroupsnewGPUBindGroupLayoutDescriptorobjects. -
For each groupDesc in groupDescs:
-
For each
GPUProgrammableStagestageDesc in the descriptor used to create pipeline:-
Let shaderStage be the
GPUShaderStageFlagsfor the shader stage at which stageDesc is used in pipeline. -
Let entryPoint be get the entry point(shaderStage, stageDesc). Assert entryPoint is not
null. -
For each resource resource statically used by entryPoint:
-
Let group be resource’s "group" decoration.
-
Let binding be resource’s "binding" decoration.
-
Let entry be a new
GPUBindGroupLayoutEntry. -
Set entry.
bindingto binding. -
Set entry.
visibilityto shaderStage. -
If resource is for a sampler binding:
-
Let samplerLayout be a new
GPUSamplerBindingLayout. -
Set entry.
samplerto samplerLayout.
-
-
If resource is for a comparison sampler binding:
-
Let samplerLayout be a new
GPUSamplerBindingLayout. -
Set samplerLayout.
typeto"comparison". -
Set entry.
samplerto samplerLayout.
-
-
If resource is for a buffer binding:
-
Let bufferLayout be a new
GPUBufferBindingLayout. -
Set bufferLayout.
minBindingSizeto resource’s minimum buffer binding size. -
If resource is for a read-only storage buffer:
-
Set bufferLayout.
typeto"read-only-storage".
-
-
If resource is for a storage buffer:
-
Set entry.
bufferto bufferLayout.
-
-
If resource is for a sampled texture binding:
-
Let textureLayout be a new
GPUTextureBindingLayout. -
If resource is a depth texture binding:
-
Set textureLayout.
sampleTypeto"depth"
Else if the sampled type of resource is:
f32and there exists a static use of resource by stageDesc in a texture builtin function call that also uses a sampler-
Set textureLayout.
sampleTypeto"float" f32otherwise-
Set textureLayout.
sampleTypeto"unfilterable-float" i32-
Set textureLayout.
sampleTypeto"sint" u32-
Set textureLayout.
sampleTypeto"uint"
-
-
Set textureLayout.
viewDimensionto resource’s dimension. -
If resource is for a multisampled texture:
-
Set textureLayout.
multisampledtotrue.
-
-
Set entry.
textureto textureLayout.
-
-
If resource is for a storage texture binding:
-
Let storageTextureLayout be a new
GPUStorageTextureBindingLayout. -
Set storageTextureLayout.
formatto resource’s format. -
Set storageTextureLayout.
viewDimensionto resource’s dimension. -
If the access mode is:
read-
Set textureLayout.
accessto"read-only". write-
Set textureLayout.
accessto"write-only". read_write-
Set textureLayout.
accessto"read-write".
-
Set entry.
storageTextureto storageTextureLayout.
-
-
Set groupCount to max(groupCount, group + 1).
-
If groupDescs[group] has an entry previousEntry with
bindingequal to binding:-
If entry has different
visibilitythan previousEntry:-
Add the bits set in entry.
visibilityinto previousEntry.visibility
-
-
If resource is for a buffer binding and entry has greater
buffer.minBindingSizethan previousEntry:-
Set previousEntry.
buffer.minBindingSizeto entry.buffer.minBindingSize.
-
-
If resource is a sampled texture binding and entry has different
texture.sampleTypethan previousEntry and both entry and previousEntry havetexture.sampleTypeof either"float"or"unfilterable-float":-
Set previousEntry.
texture.sampleTypeto"float".
-
-
If any other property is unequal between entry and previousEntry:
-
Return
null(which will cause the creation of the pipeline to fail).
-
-
If resource is a storage texture binding, entry.storageTexture.
accessis"read-write", previousEntry.storageTexture.accessis"write-only", and previousEntry.storageTexture.formatis compatible withSTORAGE_BINDINGand"read-write"according to the § 26.1.1 Plain color formats table:-
Set previousEntry.storageTexture.
accessto"read-write".
-
-
-
Else
-
Append entry to groupDescs[group].
-
-
-
-
Let groupLayouts be a new list.
-
For each i from 0 to groupCount - 1, inclusive:
-
Let groupDesc be groupDescs[i].
-
Let bindGroupLayout be the result of calling device.
createBindGroupLayout()(groupDesc). -
Set bindGroupLayout.
[[exclusivePipeline]]to pipeline. -
Append bindGroupLayout to groupLayouts.
-
-
Let desc be a new
GPUPipelineLayoutDescriptor. -
Set desc.
bindGroupLayoutsto groupLayouts. -
Return device.
createPipelineLayout()(desc).
10.1.2. GPUProgrammableStage
A GPUProgrammableStage
describes the entry point in the user-provided
GPUShaderModule
that controls one of the programmable stages of a pipeline.
Entry point names follow the rules defined in WGSL identifier comparison.
dictionary GPUProgrammableStage {required GPUShaderModule module ;USVString entryPoint ;record <USVString ,GPUPipelineConstantValue >constants = {}; };typedef double GPUPipelineConstantValue ; // May represent WGSL's bool, f32, i32, u32, and f16 if enabled.
GPUProgrammableStage
has the following members:
module, of type GPUShaderModule-
The
GPUShaderModulecontaining the code that this programmable stage will execute. entryPoint, of type USVString-
The name of the function in
modulethat this stage will use to perform its work.NOTE: Since the
entryPointdictionary member is not required, methods which consume aGPUProgrammableStagemust use the "get the entry point" algorithm to determine which entry point it refers to. constants, of type record<USVString, GPUPipelineConstantValue>, defaulting to{}-
Specifies the values of pipeline-overridable constants in the shader module
module.Each such pipeline-overridable constant is uniquely identified by a single pipeline-overridable constant identifier string, representing the pipeline constant ID of the constant if its declaration specifies one, and otherwise the constant’s identifier name.
The key of each key-value pair must equal the identifier string of one such constant, with the comparison performed according to the rules for WGSL identifier comparison. When the pipeline is executed, that constant will have the specified value.
Values are specified as
GPUPipelineConstantValue, which is adouble. They are converted to WGSL type of the pipeline-overridable constant (bool/i32/u32/f32/f16). If conversion fails, a validation error is generated.Pipeline-overridable constants defined in WGSL:@id ( 0 ) override has_point_light : bool= true ; // Algorithmic control. @id ( 1200 ) override specular_param : f32= 2.3 ; // Numeric control. @id ( 1300 ) override gain : f32; // Must be overridden. override width : f32= 0.0 ; // Specifed at the API level // using the name "width". override depth : f32; // Specifed at the API level // using the name "depth". // Must be overridden. override height = 2 * depth ; // The default value // (if not set at the API level), // depends on another // overridable constant. Corresponding JavaScript code, providing only the overrides which are required (have no defaults):
{ // ... constants: { 1300 : 2.0 , // "gain" depth: - 1 , // "depth" } } Corresponding JavaScript code, overriding all constants:
{ // ... constants: { 0 : false , // "has_point_light" 1200 : 3.0 , // "specular_param" 1300 : 2.0 , // "gain" width: 20 , // "width" depth: - 1 , // "depth" height: 15 , // "height" } }
GPUShaderStage
stage,
GPUProgrammableStage
descriptor), run the following device timeline steps:
-
If descriptor.
entryPointis provided:-
If descriptor.
modulecontains an entry point whose name equals descriptor.entryPoint, and whose shader stage equals stage, return that entry point.Otherwise, return
null.
Otherwise:
-
If there is exactly one entry point in descriptor.
modulewhose shader stage equals stage, return that entry point.Otherwise, return
null.
-
Arguments:
-
GPUShaderStagestage -
GPUProgrammableStagedescriptor -
GPUPipelineLayoutlayout -
GPUDevicedevice
All of the requirements in the following steps must be met.
If any are unmet, return false; otherwise, return true.
-
descriptor.
modulemust be valid to use with device. -
Let entryPoint be get the entry point(stage, descriptor).
-
entryPoint must not be
null. -
For each binding that is statically used by entryPoint:
-
validating shader binding(binding, layout) must return
true.
-
-
For each texture builtin function call in any of the functions in the shader stage rooted at entryPoint, if it uses a textureBinding of sampled texture or depth texture type together with a samplerBinding of
samplertype (excludingsampler_comparison):-
Let texture be the
GPUBindGroupLayoutEntrycorresponding to textureBinding. -
Let sampler be the
GPUBindGroupLayoutEntrycorresponding to samplerBinding. -
If sampler.
typeis"filtering", then texture.sampleTypemust be"float".
Note:
"comparison"samplers can also only be used with"depth"textures, because they are the only texture type that can be bound to WGSLtexture_depth_*bindings. -
-
For each key → value in descriptor.
constants:-
key must equal the pipeline-overridable constant identifier string of some pipeline-overridable constant defined in the shader module descriptor.
moduleby the rules defined in WGSL identifier comparison. The pipeline-overridable constant is not required to be statically used by entryPoint. Let the type of that constant be T. -
Converting the IDL value value to WGSL type T must not throw a
TypeError.
-
-
For each pipeline-overridable constant identifier string key which is statically used by entryPoint:
-
If the pipeline-overridable constant identified by key does not have a default value, descriptor.
constantsmust contain key.
-
-
Pipeline-creation program errors must not result from the rules of the [WGSL] specification.
Arguments:
-
shader binding declaration variable, a module-scope variable declaration reflected from a shader module
-
GPUPipelineLayoutlayout
Let bindGroup be the bind group index, and bindIndex be the binding index, of the shader binding declaration variable.
Return true if all of the following conditions are satisfied:
-
layout.
[[bindGroupLayouts]][bindGroup] contains aGPUBindGroupLayoutEntryentry whose entry.binding== bindIndex. -
If the defined binding member for entry is:
buffer-
"uniform"-
variable is declared with address space
uniform. "storage"-
variable is declared with address space
storageand access moderead_write. "read-only-storage"-
variable is declared with address space
storageand access moderead.
If entry.
buffer.minBindingSizeis not0, then it must be at least the minimum buffer binding size for the associated buffer binding variable in the shader. sampler-
"filtering"or"non-filtering"-
variable has type
sampler. "comparison"-
variable has type
sampler_comparison.
texture-
If, and only if, entry.
texture.multisampledistrue, variable has typetexture_multisampled_2d<T>ortexture_depth_multisampled_2d<T>.If entry.
texture.sampleTypeis:"float","unfilterable-float","sint"or"uint"-
variable has one of the types:
-
texture_1d<T> -
texture_2d<T> -
texture_2d_array<T> -
texture_cube<T> -
texture_cube_array<T> -
texture_3d<T> -
texture_multisampled_2d<T>
If entry.
texture.sampleTypeis:"float"or"unfilterable-float"-
The sampled type
Tisf32. "sint"-
The sampled type
Tisi32. "uint"-
The sampled type
Tisu32.
-
"depth"-
variable has one of the types:
-
texture_2d<T> -
texture_2d_array<T> -
texture_cube<T> -
texture_cube_array<T> -
texture_multisampled_2d<T> -
texture_depth_2d -
texture_depth_2d_array -
texture_depth_cube -
texture_depth_cube_array -
texture_depth_multisampled_2d
where the sampled type
Tisf32. -
If entry.
texture.viewDimensionis:"1d"-
variable has type
texture_1d<T>. "2d"-
variable has type
texture_2d<T>ortexture_multisampled_2d<T>. "2d-array"-
variable has type
texture_2d_array<T>. "cube"-
variable has type
texture_cube<T>. "cube-array"-
variable has type
texture_cube_array<T>. "3d"-
variable has type
texture_3d<T>.
storageTexture-
If entry.
storageTexture.viewDimensionis:"1d"-
variable has type
texture_storage_1d<T, A>. "2d"-
variable has type
texture_storage_2d<T, A>. "2d-array"-
variable has type
texture_storage_2d_array<T, A>. "3d"-
variable has type
texture_storage_3d<T, A>.
If entry.
storageTexture.accessis:"write-only"-
The access mode
Aiswrite. "read-only"-
The access mode
Aisread. "read-write"-
The access mode
Aisread_writeorwrite.
The texel format
Tequals entry.storageTexture.format.
-
Let T be the store type of var.
-
If T is a runtime-sized array, or contains a runtime-sized array, replace that
array<E>witharray<E, 1>.Note: This ensures there’s always enough memory for one element, which allows array indices to be clamped to the length of the array resulting in an in-memory access.
-
Return SizeOf(T).
Note: Enforcing this lower bound ensures reads and writes via the buffer variable only access memory locations within the bound region of the buffer.
10.2. GPUComputePipeline
A GPUComputePipeline
is a kind of pipeline that controls the
compute shader stage,
and can be used in GPUComputePassEncoder.
Compute inputs and outputs are all contained in the bindings,
according to the given GPUPipelineLayout.
The outputs correspond to buffer
bindings with a type of "storage"
and storageTexture
bindings with a type of
"write-only"
or
"read-write".
Stages of a compute pipeline:
-
Compute shader
[Exposed =(Window ,Worker ),SecureContext ]interface GPUComputePipeline { };GPUComputePipeline includes GPUObjectBase ;GPUComputePipeline includes GPUPipelineBase ;
10.2.1. Compute Pipeline Creation
A GPUComputePipelineDescriptor
describes a compute pipeline. See
§ 23.1 Computing for additional details.
dictionary :GPUComputePipelineDescriptor GPUPipelineDescriptorBase {required GPUProgrammableStage compute ; };
GPUComputePipelineDescriptor
has the following members:
compute, of type GPUProgrammableStage-
Describes the compute shader entry point of the pipeline.
createComputePipeline(descriptor)-
Creates a
GPUComputePipelineusing immediate pipeline creation.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createComputePipeline(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUComputePipelineDescriptor✘ ✘ Description of the GPUComputePipelineto create.Returns:
GPUComputePipelineContent timeline steps:
-
Let pipeline be ! create a new WebGPU object(this,
GPUComputePipeline, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return pipeline.
Device timeline initialization steps:-
Let layout be a new default pipeline layout for pipeline if descriptor.
layoutis"auto", and descriptor.layoutotherwise. -
All of the requirements in the following steps must be met. If any are unmet, generate a validation error, invalidate pipeline and return.
-
layout must be valid to use with this.
-
validating GPUProgrammableStage(
COMPUTE, descriptor.compute, layout, this) must succeed. -
Let entryPoint be get the entry point(
COMPUTE, descriptor.compute).Assert entryPoint is not
null. -
Let workgroupStorageUsed be the sum of roundUp(16, SizeOf(T)) over each type T of all variables with address space "workgroup" statically used by entryPoint.
workgroupStorageUsed must be ≤ device.limits.
maxComputeWorkgroupStorageSize. -
entryPoint must use ≤ device.limits.
maxComputeInvocationsPerWorkgroupper workgroup. -
Each component of entryPoint’s
workgroup_sizeattribute must be ≤ the corresponding component in [device.limits.maxComputeWorkgroupSizeX, device.limits.maxComputeWorkgroupSizeY, device.limits.maxComputeWorkgroupSizeZ].
-
-
If any pipeline-creation uncategorized errors result from the implementation of pipeline creation, generate an internal error, invalidate pipeline and return.
Note: Even if the implementation detected uncategorized errors in shader module creation, the error is surfaced here.
-
Set pipeline.
[[layout]]to layout.
-
createComputePipelineAsync(descriptor)-
Creates a
GPUComputePipelineusing async pipeline creation. The returnedPromiseresolves when the created pipeline is ready to be used without additional delay.If pipeline creation fails, the returned
Promiserejects with anGPUPipelineError. (AGPUErroris not dispatched to the device.)Note: Use of this method is preferred whenever possible, as it prevents blocking the queue timeline work on pipeline compilation.
Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createComputePipelineAsync(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUComputePipelineDescriptor✘ ✘ Description of the GPUComputePipelineto create.Returns:
Promise<GPUComputePipeline>Content timeline steps:
-
Let contentTimeline be the current Content timeline.
-
Let promise be a new promise.
-
Issue the initialization steps on the Device timeline of this.
-
Return promise.
Device timeline initialization steps:-
Let pipeline be a new
GPUComputePipelinecreated as if this.createComputePipeline()was called with descriptor, except capturing any errors as error, rather than dispatching them to the device. -
Let event occur upon the (successful or unsuccessful) completion of pipeline creation for pipeline.
-
Listen for timeline event event on this.
[[device]], handled by the subsequent steps on the device timeline of this.
Device timeline steps:-
If pipeline is valid or this is lost:
-
Issue the following steps on contentTimeline:
Content timeline steps:-
Resolve promise with pipeline.
-
-
Return.
Note: No errors are generated from a device which is lost. See § 22 Errors & Debugging.
-
-
If pipeline is invalid and error is an internal error, issue the following steps on contentTimeline, and return.
Content timeline steps:-
Reject promise with a
GPUPipelineErrorwithreason"internal".
-
-
If pipeline is invalid and error is a validation error, issue the following steps on contentTimeline, and return.
Content timeline steps:-
Reject promise with a
GPUPipelineErrorwithreason"validation".
-
-
GPUComputePipeline:
const computePipeline= gpuDevice. createComputePipeline({ layout: pipelineLayout, compute: { module: computeShaderModule, entryPoint: 'computeMain' , } });
10.3. GPURenderPipeline
A GPURenderPipeline
is a kind of pipeline that controls the
vertex
and fragment shader stages, and can be used in GPURenderPassEncoder
as well as GPURenderBundleEncoder.
Render pipeline inputs are:
-
bindings, according to the given
GPUPipelineLayout -
vertex and index buffers, described by
GPUVertexState -
the color attachments, described by
GPUColorTargetState -
optionally, the depth-stencil attachment, described by
GPUDepthStencilState
Render pipeline outputs are:
-
storageTexturebindings with aaccessof"write-only"or"read-write" -
the color attachments, described by
GPUColorTargetState -
optionally, depth-stencil attachment, described by
GPUDepthStencilState
A render pipeline is comprised of the following render stages:
-
Vertex fetch, controlled by
GPUVertexState.buffers -
Vertex shader, controlled by
GPUVertexState -
Primitive assembly, controlled by
GPUPrimitiveState -
Rasterization, controlled by
GPUPrimitiveState,GPUDepthStencilState, andGPUMultisampleState -
Fragment shader, controlled by
GPUFragmentState -
Stencil test and operation, controlled by
GPUDepthStencilState -
Depth test and write, controlled by
GPUDepthStencilState -
Output merging, controlled by
GPUFragmentState.targets
[Exposed =(Window ,Worker ),SecureContext ]interface GPURenderPipeline { };GPURenderPipeline includes GPUObjectBase ;GPURenderPipeline includes GPUPipelineBase ;
GPURenderPipeline
has the following device timeline properties:
[[descriptor]], of typeGPURenderPipelineDescriptor, readonly-
The
GPURenderPipelineDescriptordescribing this pipeline.All optional fields of
GPURenderPipelineDescriptorare defined. [[writesDepth]], of typeboolean, readonly-
True if the pipeline writes to the depth component of the depth/stencil attachment
[[writesStencil]], of typeboolean, readonly-
True if the pipeline writes to the stencil component of the depth/stencil attachment
10.3.1. Render Pipeline Creation
A GPURenderPipelineDescriptor
describes a render pipeline by
configuring each
of the render stages. See § 23.2 Rendering for additional details.
dictionary :GPURenderPipelineDescriptor GPUPipelineDescriptorBase {required GPUVertexState vertex ;GPUPrimitiveState primitive = {};GPUDepthStencilState depthStencil ;GPUMultisampleState multisample = {};GPUFragmentState fragment ; };
GPURenderPipelineDescriptor
has the following members:
vertex, of type GPUVertexState-
Describes the vertex shader entry point of the pipeline and its input buffer layouts.
primitive, of type GPUPrimitiveState, defaulting to{}-
Describes the primitive-related properties of the pipeline.
depthStencil, of type GPUDepthStencilState-
Describes the optional depth-stencil properties, including the testing, operations, and bias.
multisample, of type GPUMultisampleState, defaulting to{}-
Describes the multi-sampling properties of the pipeline.
fragment, of type GPUFragmentState-
Describes the fragment shader entry point of the pipeline and its output colors. If not provided, the § 23.2.8 No Color Output mode is enabled.
createRenderPipeline(descriptor)-
Creates a
GPURenderPipelineusing immediate pipeline creation.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createRenderPipeline(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderPipelineDescriptor✘ ✘ Description of the GPURenderPipelineto create.Returns:
GPURenderPipelineContent timeline steps:
-
If descriptor.
fragmentis provided:-
For each non-
nullcolorState of descriptor.fragment.targets:-
? Validate texture format required features of colorState.
formatwith this.[[device]].
-
-
-
If descriptor.
depthStencilis provided:-
? Validate texture format required features of descriptor.
depthStencil.formatwith this.[[device]].
-
-
Let pipeline be ! create a new WebGPU object(this,
GPURenderPipeline, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return pipeline.
Device timeline initialization steps:-
Let layout be a new default pipeline layout for pipeline if descriptor.
layoutis"auto", and descriptor.layoutotherwise. -
All of the requirements in the following steps must be met. If any are unmet, generate a validation error, invalidate pipeline, and return.
-
layout must be valid to use with this.
-
validating GPURenderPipelineDescriptor(descriptor, layout, this) must succeed.
-
Let vertexBufferCount be the index of the last non-null entry in descriptor.
vertex.buffers, plus 1; or 0 if there are none. -
layout.
[[bindGroupLayouts]].size + vertexBufferCount must be ≤ this.[[device]].[[limits]].maxBindGroupsPlusVertexBuffers.
-
-
If any pipeline-creation uncategorized errors result from the implementation of pipeline creation, generate an internal error, invalidate pipeline and return.
Note: Even if the implementation detected uncategorized errors in shader module creation, the error is surfaced here.
-
Set pipeline.
[[descriptor]]to descriptor. -
Set pipeline.
[[writesDepth]]to false. -
Set pipeline.
[[writesStencil]]to false. -
Let depthStencil be descriptor.
depthStencil. -
If depthStencil is not null:
-
If depthStencil.
depthWriteEnabledis provided:-
Set pipeline.
[[writesDepth]]to depthStencil.depthWriteEnabled.
-
-
If depthStencil.
stencilWriteMaskis not 0:-
Let stencilFront be depthStencil.
stencilFront. -
Let stencilBack be depthStencil.
stencilBack. -
If cullMode is not
"front", and any of stencilFront.passOp, stencilFront.depthFailOp, or stencilFront.failOpis not"keep":-
Set pipeline.
[[writesStencil]]to true.
-
-
If cullMode is not
"back", and any of stencilBack.passOp, stencilBack.depthFailOp, or stencilBack.failOpis not"keep":-
Set pipeline.
[[writesStencil]]to true.
-
-
-
-
Set pipeline.
[[layout]]to layout.
-
createRenderPipelineAsync(descriptor)-
Creates a
GPURenderPipelineusing async pipeline creation. The returnedPromiseresolves when the created pipeline is ready to be used without additional delay.If pipeline creation fails, the returned
Promiserejects with anGPUPipelineError. (AGPUErroris not dispatched to the device.)Note: Use of this method is preferred whenever possible, as it prevents blocking the queue timeline work on pipeline compilation.
Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createRenderPipelineAsync(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderPipelineDescriptor✘ ✘ Description of the GPURenderPipelineto create.Returns:
Promise<GPURenderPipeline>Content timeline steps:
-
Let contentTimeline be the current Content timeline.
-
Let promise be a new promise.
-
Issue the initialization steps on the Device timeline of this.
-
Return promise.
Device timeline initialization steps:-
Let pipeline be a new
GPURenderPipelinecreated as if this.createRenderPipeline()was called with descriptor, except capturing any errors as error, rather than dispatching them to the device. -
Let event occur upon the (successful or unsuccessful) completion of pipeline creation for pipeline.
-
Listen for timeline event event on this.
[[device]], handled by the subsequent steps on the device timeline of this.
Device timeline steps:-
If pipeline is valid or this is lost:
-
Issue the following steps on contentTimeline:
Content timeline steps:-
Resolve promise with pipeline.
-
-
Return.
Note: No errors are generated from a device which is lost. See § 22 Errors & Debugging.
-
-
If pipeline is invalid and error is an internal error, issue the following steps on contentTimeline, and return.
Content timeline steps:-
Reject promise with a
GPUPipelineErrorwithreason"internal".
-
-
If pipeline is invalid and error is a validation error, issue the following steps on contentTimeline, and return.
Content timeline steps:-
Reject promise with a
GPUPipelineErrorwithreason"validation".
-
-
Arguments:
-
GPURenderPipelineDescriptordescriptor -
GPUPipelineLayoutlayout -
GPUDevicedevice
Device timeline steps:
-
Return
trueif all of the following conditions are satisfied:-
validating GPUVertexState(device, descriptor.
vertex, layout) succeeds. -
If descriptor.
fragmentis provided:-
validating GPUFragmentState(device, descriptor.
fragment, layout) succeeds. -
If the sample_mask builtin is a shader stage output of descriptor.
fragment:-
descriptor.
multisample.alphaToCoverageEnabledisfalse.
-
-
If the frag_depth builtin is a shader stage output of descriptor.
fragment:-
descriptor.
depthStencilmust be provided, and descriptor.depthStencil.formatmust have a depth aspect.
-
-
-
validating GPUPrimitiveState(descriptor.
primitive, device) succeeds. -
If descriptor.
depthStencilis provided:-
validating GPUDepthStencilState(descriptor.
depthStencil, descriptor.primitive.topology) succeeds.
-
-
validating GPUMultisampleState(descriptor.
multisample) succeeds. -
If descriptor.
multisample.alphaToCoverageEnabledis true: -
There must exist at least one attachment, either:
-
A descriptor.
depthStencil.
-
validating inter-stage interfaces(device, descriptor) returns
true.
-
Arguments:
-
GPUDevicedevice -
GPURenderPipelineDescriptordescriptor
Returns: boolean
Device timeline steps:
-
Let maxVertexShaderOutputVariables be device.limits.
maxInterStageShaderVariables. -
Let maxVertexShaderOutputLocation be device.limits.
maxInterStageShaderVariables- 1. -
If descriptor.
primitive.topologyis"point-list":-
Decrement maxVertexShaderOutputVariables by 1.
-
-
If clip_distances is declared in the output of descriptor.
vertex:-
Let clipDistancesSize be the array size of clip_distances.
-
Decrement maxVertexShaderOutputVariables by ceil(clipDistancesSize / 4).
-
Decrement maxVertexShaderOutputLocation by ceil(clipDistancesSize / 4).
-
-
Return
falseif any of the following requirements are unmet: -
If descriptor.
fragmentis provided:-
Let maxFragmentShaderInputVariables be device.limits.
maxInterStageShaderVariables. -
If any of the
front_facing,sample_index, orsample_maskbuiltins are an input of descriptor.fragment:-
Decrement maxFragmentShaderInputVariables by 1.
-
-
Return
falseif any of the following requirements are unmet:-
For each user-defined input of descriptor.
fragmentthere must be a user-defined output of descriptor.vertexthat location, type, and interpolation of the input.Note: Vertex-only pipelines can have user-defined outputs in the vertex stage; their values will be discarded.
-
There must be no more than maxFragmentShaderInputVariables user-defined inputs for descriptor.
fragment.
-
-
Assert that the location of each user-defined input of descriptor.
fragmentis less than device.limits.maxInterStageShaderVariables. (This follows from the above rules.)
-
-
Return
true.
GPURenderPipeline:
const renderPipeline= gpuDevice. createRenderPipeline({ layout: pipelineLayout, vertex: { module: shaderModule, entryPoint: 'vertexMain' }, fragment: { module: shaderModule, entryPoint: 'fragmentMain' , targets: [{ format: 'bgra8unorm' , }], } });
10.3.2. Primitive State
dictionary {GPUPrimitiveState GPUPrimitiveTopology topology = "triangle-list";GPUIndexFormat stripIndexFormat ;GPUFrontFace frontFace = "ccw";GPUCullMode cullMode = "none"; // Requires "depth-clip-control" feature.boolean unclippedDepth =false ; };
GPUPrimitiveState
has the following members, which describe how a GPURenderPipeline
constructs and rasterizes primitives from its vertex inputs:
topology, of type GPUPrimitiveTopology, defaulting to"triangle-list"-
The type of primitive to be constructed from the vertex inputs.
stripIndexFormat, of type GPUIndexFormat-
For pipelines with strip topologies (
"line-strip"or"triangle-strip"), this determines the index buffer format and primitive restart value ("uint16"/0xFFFFor"uint32"/0xFFFFFFFF). It is not allowed on pipelines with non-strip topologies.Note: Some implementations require knowledge of the primitive restart value to compile pipeline state objects.
To use a strip-topology pipeline with an indexed draw call (
drawIndexed()ordrawIndexedIndirect()), this must be set, and it must match the index buffer format used with the draw call (set insetIndexBuffer()).See § 23.2.3 Primitive Assembly for additional details.
frontFace, of type GPUFrontFace, defaulting to"ccw"-
Defines which polygons are considered front-facing.
cullMode, of type GPUCullMode, defaulting to"none"-
Defines which polygon orientation will be culled, if any.
unclippedDepth, of type boolean, defaulting tofalse-
If true, indicates that depth clipping is disabled.
Requires the
"depth-clip-control"feature to be enabled.
-
GPUPrimitiveStatedescriptor -
GPUDevicedevice
Device timeline steps:
-
Return
trueif all of the following conditions are satisfied:-
If descriptor.
topologyis not"line-strip"or"triangle-strip":-
descriptor.
stripIndexFormatmust not be provided.
-
-
If descriptor.
unclippedDepthistrue:-
"depth-clip-control"must be enabled for device.
-
-
enum {GPUPrimitiveTopology "point-list" ,"line-list" ,"line-strip" ,"triangle-list" ,"triangle-strip" , };
GPUPrimitiveTopology
defines the primitive type draw calls made with a GPURenderPipeline
will use. See § 23.2.5 Rasterization for additional details:
"point-list"-
Each vertex defines a point primitive.
"line-list"-
Each consecutive pair of two vertices defines a line primitive.
"line-strip"-
Each vertex after the first defines a line primitive between it and the previous vertex.
"triangle-list"-
Each consecutive triplet of three vertices defines a triangle primitive.
"triangle-strip"-
Each vertex after the first two defines a triangle primitive between it and the previous two vertices.
enum {GPUFrontFace "ccw" ,"cw" , };
GPUFrontFace
defines which polygons are considered front-facing by a GPURenderPipeline.
See § 23.2.5.4 Polygon Rasterization for additional details:
"ccw"-
Polygons with vertices whose framebuffer coordinates are given in counter-clockwise order are considered front-facing.
"cw"-
Polygons with vertices whose framebuffer coordinates are given in clockwise order are considered front-facing.
enum {GPUCullMode "none" ,"front" ,"back" , };
GPUPrimitiveTopology
defines which polygons will be culled by draw calls made with a
GPURenderPipeline.
See § 23.2.5.4 Polygon Rasterization for additional details:
"none"-
No polygons are discarded.
"front"-
Front-facing polygons are discarded.
"back"-
Back-facing polygons are discarded.
Note: GPUFrontFace
and GPUCullMode
have no effect on "point-list",
"line-list",
or "line-strip"
topologies.
10.3.3. Multisample State
dictionary {GPUMultisampleState GPUSize32 count = 1;GPUSampleMask mask = 0xFFFFFFFF;boolean alphaToCoverageEnabled =false ; };
GPUMultisampleState
has the following members, which describe how a GPURenderPipeline
interacts with a render pass’s multisampled attachments.
count, of type GPUSize32, defaulting to1-
Number of samples per pixel. This
GPURenderPipelinewill be compatible only with attachment textures (colorAttachmentsanddepthStencilAttachment) with matchingsampleCounts. mask, of type GPUSampleMask, defaulting to0xFFFFFFFF-
Mask determining which samples are written to.
alphaToCoverageEnabled, of type boolean, defaulting tofalse-
When
trueindicates that a fragment’s alpha channel should be used to generate a sample coverage mask.
-
GPUMultisampleStatedescriptor
Device timeline steps:
-
Return
trueif all of the following conditions are satisfied:-
descriptor.
countmust be either 1 or 4. -
If descriptor.
alphaToCoverageEnabledistrue:-
descriptor.
count> 1.
-
-
10.3.4. Fragment State
dictionary :GPUFragmentState GPUProgrammableStage {required sequence <GPUColorTargetState ?>targets ; };
targets, of typesequence<GPUColorTargetState?>-
A list of
GPUColorTargetStatedefining the formats and behaviors of the color targets this pipeline writes to.
Arguments:
-
GPUDevicedevice -
GPUFragmentStatedescriptor -
GPUPipelineLayoutlayout
Device timeline steps:
-
Return
trueif all of the following requirements are met:-
validating GPUProgrammableStage(
FRAGMENT, descriptor, layout, device) succeeds. -
descriptor.
targets.size must be ≤ device.[[limits]].maxColorAttachments. -
Let entryPoint be get the entry point(
FRAGMENT, descriptor). -
Let usesDualSourceBlending be
false. -
For each index of the indices of descriptor.
targetscontaining a non-nullvalue colorState:-
colorState.
formatmust be listed in § 26.1.1 Plain color formats withRENDER_ATTACHMENTcapability. -
colorState.
writeMaskmust be < 16. -
If colorState.
blendis provided:-
colorState.
blend.colormust be a valid GPUBlendComponent. -
colorState.
blend.alphamust be a valid GPUBlendComponent. -
If colorState.
blend.color.srcFactoror colorState.blend.color.dstFactoror colorState.blend.alpha.srcFactoror colorState.blend.alpha.dstFactoruses the second input of the corresponding blending unit (is any of"src1","one-minus-src1","src1-alpha","one-minus-src1-alpha"), then:-
Set usesDualSourceBlending to
true.
-
-
For each shader stage output value output with location attribute equal to index in entryPoint:
-
For each component in colorState.
format, there must be a corresponding component in output. (That is, RGBA requires vec4, RGB requires vec3 or vec4, RG requires vec2 or vec3 or vec4.) -
If the
GPUTextureSampleTypes for colorState.format(defined in § 26.1 Texture Format Capabilities) are:"float"and/or"unfilterable-float"-
output must have a floating-point scalar type.
"sint"-
output must have a signed integer scalar type.
"uint"-
output must have an unsigned integer scalar type.
-
If colorState.
blendis provided and colorState.blend.color.srcFactoror .dstFactoruses the source alpha (is any of"src-alpha","one-minus-src-alpha","src-alpha-saturated","src1-alpha"or"one-minus-src1-alpha"), then:-
output must have an alpha channel (that is, it must be a vec4).
-
-
-
If colorState.
writeMaskis not 0:-
entryPoint must have a shader stage output with location equal to index and blend_src omitted or equal to 0.
-
-
-
If usesDualSourceBlending is
true:-
All the shader stage outputs with location in entryPoint must be in one struct and use dual source blending.
-
Validating GPUFragmentState’s color attachment bytes per sample(device, descriptor.
targets) succeeds.
-
Arguments:
-
GPUDevicedevice -
sequence<
GPUColorTargetState?> targets
Device timeline steps:
-
Let formats be an empty list<
GPUTextureFormat?> -
For each target in targets:
-
Calculating color attachment bytes per sample(formats) must be ≤ device.
[[limits]].maxColorAttachmentBytesPerSample.
Note: The fragment shader may output more values than what the pipeline uses. If that is the case the values are ignored.
GPUBlendComponent
component is a valid GPUBlendComponent with logical
device device if it meetsthe following requirements:
10.3.5. Color Target State
dictionary {GPUColorTargetState required GPUTextureFormat format ;GPUBlendState blend ;GPUColorWriteFlags writeMask = 0xF; // GPUColorWrite.ALL };
format, of type GPUTextureFormat-
The
GPUTextureFormatof this color target. The pipeline will only be compatible withGPURenderPassEncoders which use aGPUTextureViewof this format in the corresponding color attachment. blend, of type GPUBlendState-
The blending behavior for this color target. If left undefined, disables blending for this color target.
writeMask, of type GPUColorWriteFlags, defaulting to0xF-
Bitmask controlling which channels are are written to when drawing to this color target.
dictionary {GPUBlendState required GPUBlendComponent color ;required GPUBlendComponent alpha ; };
color, of type GPUBlendComponent-
Defines the blending behavior of the corresponding render target for color channels.
alpha, of type GPUBlendComponent-
Defines the blending behavior of the corresponding render target for the alpha channel.
typedef [EnforceRange ]unsigned long ; [GPUColorWriteFlags Exposed =(Window ,Worker ),SecureContext ]namespace {GPUColorWrite const GPUFlagsConstant = 0x1;RED const GPUFlagsConstant = 0x2;GREEN const GPUFlagsConstant = 0x4;BLUE const GPUFlagsConstant = 0x8;ALPHA const GPUFlagsConstant = 0xF; };ALL
10.3.5.1. Blend State
dictionary {GPUBlendComponent GPUBlendOperation operation = "add";GPUBlendFactor srcFactor = "one";GPUBlendFactor dstFactor = "zero"; };
GPUBlendComponent
has the following members, which describe how the color or alpha components
of a fragment are blended:
operation, of type GPUBlendOperation, defaulting to"add"-
Defines the
GPUBlendOperationused to calculate the values written to the target attachment components. srcFactor, of type GPUBlendFactor, defaulting to"one"-
Defines the
GPUBlendFactoroperation to be performed on values from the fragment shader. dstFactor, of type GPUBlendFactor, defaulting to"zero"-
Defines the
GPUBlendFactoroperation to be performed on values from the target attachment.
The following tables use this notation to describe color components for a given fragment location:
RGBAsrc
| Color output by the fragment shader for the color attachment. If the shader doesn’t return an alpha channel, src-alpha blend factors cannot be used. |
RGBAsrc1
| Color output by the fragment shader for the color attachment with
"@blend_src" attribute
equal to 1.
If the shader doesn’t return an alpha channel, src1-alpha blend factors cannot be used.
|
RGBAdst
| Color currently in the color attachment.
Missing green/blue/alpha channels default to 0, 0, 1, respectively.
|
RGBAconst
| The current [[blendConstant]].
|
RGBAsrcFactor
| The source blend factor components, as defined by srcFactor.
|
RGBAdstFactor
| The destination blend factor components, as defined by dstFactor.
|
enum {GPUBlendFactor "zero" ,"one" ,"src" ,"one-minus-src" ,"src-alpha" ,"one-minus-src-alpha" ,"dst" ,"one-minus-dst" ,"dst-alpha" ,"one-minus-dst-alpha" ,"src-alpha-saturated" ,"constant" ,"one-minus-constant" ,"src1" ,"one-minus-src1" ,"src1-alpha" ,"one-minus-src1-alpha" , };
GPUBlendFactor
defines how either a source or destination blend factors is calculated:
| GPUBlendFactor | Blend factor RGBA components | Feature |
|---|---|---|
"zero"
| (0, 0, 0, 0)
| |
"one"
| (1, 1, 1, 1)
| |
"src"
| (Rsrc, Gsrc, Bsrc, Asrc)
| |
"one-minus-src"
| (1 - Rsrc, 1 - Gsrc, 1 - Bsrc, 1 - Asrc)
| |
"src-alpha"
| (Asrc, Asrc, Asrc, Asrc)
| |
"one-minus-src-alpha"
| (1 - Asrc, 1 - Asrc, 1 - Asrc, 1 - Asrc)
| |
"dst"
| (Rdst, Gdst, Bdst, Adst)
| |
"one-minus-dst"
| (1 - Rdst, 1 - Gdst, 1 - Bdst, 1 - Adst)
| |
"dst-alpha"
| (Adst, Adst, Adst, Adst)
| |
"one-minus-dst-alpha"
| (1 - Adst, 1 - Adst, 1 - Adst, 1 - Adst)
| |
"src-alpha-saturated"
| (min(Asrc, 1 - Adst), min(Asrc, 1 - Adst), min(Asrc, 1 - Adst), 1)
| |
"constant"
| (Rconst, Gconst, Bconst, Aconst)
| |
"one-minus-constant"
| (1 - Rconst, 1 - Gconst, 1 - Bconst, 1 - Aconst)
| |
"src1"
| (Rsrc1, Gsrc1, Bsrc1, Asrc1)
| dual-source-blending
|
"one-minus-src1"
| (1 - Rsrc1, 1 - Gsrc1, 1 - Bsrc1, 1 - Asrc1)
| |
"src1-alpha"
| (Asrc1, Asrc1, Asrc1, Asrc1)
| |
"one-minus-src1-alpha"
| (1 - Asrc1, 1 - Asrc1, 1 - Asrc1, 1 - Asrc1)
|
enum {GPUBlendOperation "add" ,"subtract" ,"reverse-subtract" ,"min" ,"max" , };
GPUBlendOperation
defines the algorithm used to combine source and destination blend factors:
| GPUBlendOperation | RGBA Components |
|---|---|
"add"
| RGBAsrc × RGBAsrcFactor + RGBAdst × RGBAdstFactor
|
"subtract"
| RGBAsrc × RGBAsrcFactor - RGBAdst × RGBAdstFactor
|
"reverse-subtract"
| RGBAdst × RGBAdstFactor - RGBAsrc × RGBAsrcFactor
|
"min"
| min(RGBAsrc, RGBAdst)
|
"max"
| max(RGBAsrc, RGBAdst)
|
10.3.6. Depth/Stencil State
dictionary {GPUDepthStencilState required GPUTextureFormat format ;boolean depthWriteEnabled ;GPUCompareFunction depthCompare ;GPUStencilFaceState stencilFront = {};GPUStencilFaceState stencilBack = {};GPUStencilValue stencilReadMask = 0xFFFFFFFF;GPUStencilValue stencilWriteMask = 0xFFFFFFFF;GPUDepthBias depthBias = 0;float depthBiasSlopeScale = 0;float depthBiasClamp = 0; };
GPUDepthStencilState
has the following members, which describe how a GPURenderPipeline
will affect a render pass’s depthStencilAttachment:
format, of type GPUTextureFormat-
The
formatofdepthStencilAttachmentthisGPURenderPipelinewill be compatible with. depthWriteEnabled, of type boolean-
Indicates if this
GPURenderPipelinecan modifydepthStencilAttachmentdepth values. depthCompare, of type GPUCompareFunction-
The comparison operation used to test fragment depths against
depthStencilAttachmentdepth values. stencilFront, of type GPUStencilFaceState, defaulting to{}-
Defines how stencil comparisons and operations are performed for front-facing primitives.
stencilBack, of type GPUStencilFaceState, defaulting to{}-
Defines how stencil comparisons and operations are performed for back-facing primitives.
stencilReadMask, of type GPUStencilValue, defaulting to0xFFFFFFFF-
Bitmask controlling which
depthStencilAttachmentstencil value bits are read when performing stencil comparison tests. stencilWriteMask, of type GPUStencilValue, defaulting to0xFFFFFFFF-
Bitmask controlling which
depthStencilAttachmentstencil value bits are written to when performing stencil operations. depthBias, of type GPUDepthBias, defaulting to0-
Constant depth bias added to each triangle fragment. See biased fragment depth for details.
depthBiasSlopeScale, of type float, defaulting to0-
Depth bias that scales with the triangle fragment’s slope. See biased fragment depth for details.
depthBiasClamp, of type float, defaulting to0-
The maximum depth bias of a triangle fragment. See biased fragment depth for details.
Note: depthBias,
depthBiasSlopeScale,
and
depthBiasClamp
have no effect on "point-list",
"line-list",
and "line-strip"
primitives, and
must be 0.
depthStencilAttachment
attachment when drawing using
GPUDepthStencilState
state is calculated by running the following queue timeline steps:
-
Let r be the minimum positive representable value >
0in the format converted to a 32-bit float. -
Let maxDepthSlope be the maximum of the horizontal and vertical slopes of the fragment’s depth value.
-
If format is a unorm format:
-
Let bias be
(float)state..depthBias* r + state.depthBiasSlopeScale* maxDepthSlope
-
-
Otherwise, if format is a float format:
-
Let bias be
(float)state..depthBias* 2^(exp(max depth in primitive) - r) + state.depthBiasSlopeScale* maxDepthSlope
-
-
If state.
depthBiasClamp>0:-
Set bias to
min(state..depthBiasClamp, bias)
-
-
Otherwise if state.
depthBiasClamp<0:-
Set bias to
max(state..depthBiasClamp, bias)
-
-
If state.
depthBias≠0or state.depthBiasSlopeScale≠0:-
Set the fragment depth value to
fragment depth value + bias
-
Arguments:
-
GPUDepthStencilStatedescriptor -
GPUPrimitiveTopologytopology
Device timeline steps:
-
Return
trueif, and only if, all of the following conditions are satisfied:-
descriptor.
formatis a depth-or-stencil format. -
If descriptor.
depthWriteEnabledistrueor descriptor.depthCompareis provided and not"always":-
descriptor.
formatmust have a depth component.
-
-
If descriptor.
stencilFrontor descriptor.stencilBackare not the default values:-
descriptor.
formatmust have a stencil component.
-
-
If descriptor.
formathas a depth component:-
descriptor.
depthWriteEnabledmust be provided. -
descriptor.
depthComparemust be provided if:-
descriptor.
depthWriteEnabledistrue, or -
descriptor.
stencilFront.depthFailOpis not"keep", or -
descriptor.
stencilBack.depthFailOpis not"keep".
-
-
-
If topology is
"point-list","line-list", or"line-strip":-
descriptor.
depthBiasmust be 0. -
descriptor.
depthBiasSlopeScalemust be 0. -
descriptor.
depthBiasClampmust be 0.
-
-
dictionary {GPUStencilFaceState GPUCompareFunction compare = "always";GPUStencilOperation failOp = "keep";GPUStencilOperation depthFailOp = "keep";GPUStencilOperation passOp = "keep"; };
GPUStencilFaceState
has the following members, which describe how stencil comparisons and
operations are performed:
compare, of type GPUCompareFunction, defaulting to"always"-
The
GPUCompareFunctionused when testing the[[stencilReference]]value against the fragment’sdepthStencilAttachmentstencil values. failOp, of type GPUStencilOperation, defaulting to"keep"-
The
GPUStencilOperationperformed if the fragment stencil comparison test described bycomparefails. depthFailOp, of type GPUStencilOperation, defaulting to"keep"-
The
GPUStencilOperationperformed if the fragment depth comparison described bydepthComparefails. passOp, of type GPUStencilOperation, defaulting to"keep"-
The
GPUStencilOperationperformed if the fragment stencil comparison test described bycomparepasses.
enum {GPUStencilOperation "keep" ,"zero" ,"replace" ,"invert" ,"increment-clamp" ,"decrement-clamp" ,"increment-wrap" ,"decrement-wrap" , };
GPUStencilOperation
defines the following operations:
"keep"-
Keep the current stencil value.
"zero"-
Set the stencil value to
0. "replace"-
Set the stencil value to
[[stencilReference]]. "invert"-
Bitwise-invert the current stencil value.
"increment-clamp"-
Increments the current stencil value, clamping to the maximum representable value of the
depthStencilAttachment’s stencil aspect. "decrement-clamp"-
Decrement the current stencil value, clamping to
0. "increment-wrap"-
Increments the current stencil value, wrapping to zero if the value exceeds the maximum representable value of the
depthStencilAttachment’s stencil aspect. "decrement-wrap"-
Decrement the current stencil value, wrapping to the maximum representable value of the
depthStencilAttachment’s stencil aspect if the value goes below0.
10.3.7. Vertex State
enum {GPUIndexFormat "uint16" ,"uint32" , };
The index format determines both the data type of index values in a buffer and, when used with
strip primitive topologies ("line-strip"
or
"triangle-strip")
also specifies the primitive restart value. The
primitive restart
value indicates which index value indicates that a new primitive
should be started rather than continuing to construct the triangle strip with the prior indexed
vertices.
GPUPrimitiveStates
that specify a strip primitive topology must specify a
stripIndexFormat
if they are used for indexed draws
so that the primitive restart value that will be used is known at pipeline
creation time. GPUPrimitiveStates
that specify a list primitive
topology will use the index format passed to setIndexBuffer()
when doing indexed rendering.
| Index format | Byte size | Primitive restart value |
|---|---|---|
"uint16"
| 2 | 0xFFFF |
"uint32"
| 4 | 0xFFFFFFFF |
10.3.7.1. Vertex Formats
The GPUVertexFormat
of a vertex attribute indicates how data from a vertex buffer will
be interpreted and exposed to the shader. The name of the format specifies the order of components,
bits per component, and vertex data type for the component.
Each vertex data type can map to any WGSL scalar type of the same base type, regardless of the bits per component:
| Vertex format prefix | Vertex data type | Compatible WGSL types |
|---|---|---|
uint
| unsigned int | u32
|
sint
| signed int | i32
|
unorm
| unsigned normalized | f16, f32
|
snorm
| signed normalized | |
float
| floating point |
The multi-component formats specify the number of components after "x". Mismatches in the number of components between the vertex format and shader type are allowed, with components being either dropped or filled with default values to compensate.
"unorm8x2"
and byte values [0x7F, 0xFF]
can be accessed in the shader with the following types:
| Shader type | Shader value |
|---|---|
f16
| 0.5h
|
f32
| 0.5f
|
vec2<f16>
| vec2(0.5h, 1.0h)
|
vec2<f32>
| vec2(0.5f, 1.0f)
|
vec3<f16>
| vec2(0.5h, 1.0h, 0.0h)
|
vec3<f32>
| vec2(0.5f, 1.0f, 0.0f)
|
vec4<f16>
| vec2(0.5h, 1.0h, 0.0h, 1.0h)
|
vec4<f32>
| vec2(0.5f, 1.0f, 0.0f, 1.0f)
|
See § 23.2.2 Vertex Processing for additional information about how vertex formats are exposed in the shader.
enum {GPUVertexFormat "uint8" ,"uint8x2" ,"uint8x4" ,"sint8" ,"sint8x2" ,"sint8x4" ,"unorm8" ,"unorm8x2" ,"unorm8x4" ,"snorm8" ,"snorm8x2" ,"snorm8x4" ,"uint16" ,"uint16x2" ,"uint16x4" ,"sint16" ,"sint16x2" ,"sint16x4" ,"unorm16" ,"unorm16x2" ,"unorm16x4" ,"snorm16" ,"snorm16x2" ,"snorm16x4" ,"float16" ,"float16x2" ,"float16x4" ,"float32" ,"float32x2" ,"float32x3" ,"float32x4" ,"uint32" ,"uint32x2" ,"uint32x3" ,"uint32x4" ,"sint32" ,"sint32x2" ,"sint32x3" ,"sint32x4" ,"unorm10-10-10-2" ,"unorm8x4-bgra" , };
| Vertex format | Data type | Components | byteSize | Example WGSL type |
|---|---|---|---|---|
"uint8"
| unsigned int | 1 | 1 | u32
|
"uint8x2"
| unsigned int | 2 | 2 | vec2<u32>
|
"uint8x4"
| unsigned int | 4 | 4 | vec4<u32>
|
"sint8"
| signed int | 1 | 1 | i32
|
"sint8x2"
| signed int | 2 | 2 | vec2<i32>
|
"sint8x4"
| signed int | 4 | 4 | vec4<i32>
|
"unorm8"
| unsigned normalized | 1 | 1 | f32
|
"unorm8x2"
| unsigned normalized | 2 | 2 | vec2<f32>
|
"unorm8x4"
| unsigned normalized | 4 | 4 | vec4<f32>
|
"snorm8"
| signed normalized | 1 | 1 | f32
|
"snorm8x2"
| signed normalized | 2 | 2 | vec2<f32>
|
"snorm8x4"
| signed normalized | 4 | 4 | vec4<f32>
|
"uint16"
| unsigned int | 1 | 2 | u32
|
"uint16x2"
| unsigned int | 2 | 4 | vec2<u32>
|
"uint16x4"
| unsigned int | 4 | 8 | vec4<u32>
|
"sint16"
| signed int | 1 | 2 | i32
|
"sint16x2"
| signed int | 2 | 4 | vec2<i32>
|
"sint16x4"
| signed int | 4 | 8 | vec4<i32>
|
"unorm16"
| unsigned normalized | 1 | 2 | f32
|
"unorm16x2"
| unsigned normalized | 2 | 4 | vec2<f32>
|
"unorm16x4"
| unsigned normalized | 4 | 8 | vec4<f32>
|
"snorm16"
| signed normalized | 1 | 2 | f32
|
"snorm16x2"
| signed normalized | 2 | 4 | vec2<f32>
|
"snorm16x4"
| signed normalized | 4 | 8 | vec4<f32>
|
"float16"
| float | 1 | 2 | f32
|
"float16x2"
| float | 2 | 4 | vec2<f16>
|
"float16x4"
| float | 4 | 8 | vec4<f16>
|
"float32"
| float | 1 | 4 | f32
|
"float32x2"
| float | 2 | 8 | vec2<f32>
|
"float32x3"
| float | 3 | 12 | vec3<f32>
|
"float32x4"
| float | 4 | 16 | vec4<f32>
|
"uint32"
| unsigned int | 1 | 4 | u32
|
"uint32x2"
| unsigned int | 2 | 8 | vec2<u32>
|
"uint32x3"
| unsigned int | 3 | 12 | vec3<u32>
|
"uint32x4"
| unsigned int | 4 | 16 | vec4<u32>
|
"sint32"
| signed int | 1 | 4 | i32
|
"sint32x2"
| signed int | 2 | 8 | vec2<i32>
|
"sint32x3"
| signed int | 3 | 12 | vec3<i32>
|
"sint32x4"
| signed int | 4 | 16 | vec4<i32>
|
"unorm10-10-10-2"
| unsigned normalized | 4 | 4 | vec4<f32>
|
"unorm8x4-bgra"
| unsigned normalized | 4 | 4 | vec4<f32>
|
enum {GPUVertexStepMode "vertex" ,"instance" , };
The step mode configures how an address for vertex buffer data is computed, based on the current vertex or instance index:
"vertex"-
The address is advanced by
arrayStridefor each vertex, and reset between instances. "instance"-
The address is advanced by
arrayStridefor each instance.
dictionary :GPUVertexState GPUProgrammableStage {sequence <GPUVertexBufferLayout ?>buffers = []; };
buffers, of typesequence<GPUVertexBufferLayout?>, defaulting to[]-
A list of
GPUVertexBufferLayouts, each defining the layout of vertex attribute data in a vertex buffer used by this pipeline.
A vertex buffer is,
conceptually, a view into buffer memory as an array of structures.
arrayStride
is the stride, in bytes, between elements of that array.
Each element of a vertex buffer is like a structure with a memory layout defined by its
attributes,
which describe the members of the structure.
Each GPUVertexAttribute
describes its
format
and its
offset,
in bytes, within the structure.
Each attribute appears as a separate input in a vertex shader, each bound by a numeric location,
which is specified by shaderLocation.
Every location must be unique within the GPUVertexState.
dictionary {GPUVertexBufferLayout required GPUSize64 arrayStride ;GPUVertexStepMode stepMode = "vertex";required sequence <GPUVertexAttribute >attributes ; };
arrayStride, of type GPUSize64-
The stride, in bytes, between elements of this array.
stepMode, of type GPUVertexStepMode, defaulting to"vertex"-
Whether each element of this array represents per-vertex data or per-instance data
attributes, of type sequence<GPUVertexAttribute>-
An array defining the layout of the vertex attributes within each element.
dictionary {GPUVertexAttribute required GPUVertexFormat format ;required GPUSize64 offset ;required GPUIndex32 shaderLocation ; };
format, of type GPUVertexFormat-
The
GPUVertexFormatof the attribute. offset, of type GPUSize64-
The offset, in bytes, from the beginning of the element to the data for the attribute.
shaderLocation, of type GPUIndex32-
The numeric location associated with this attribute, which will correspond with a "@location" attribute declared in the
vertex.module.
Arguments:
-
GPUDevicedevice -
GPUVertexBufferLayoutdescriptor
Device timeline steps:
-
Return
true, if and only if, all of the following conditions are satisfied:-
descriptor.
arrayStride≤ device.[[device]].[[limits]].maxVertexBufferArrayStride. -
descriptor.
arrayStrideis a multiple of 4. -
For each attribute attrib in the list descriptor.
attributes:-
If descriptor.
arrayStrideis zero:-
attrib.
offset+ byteSize(attrib.format) ≤ device.[[device]].[[limits]].maxVertexBufferArrayStride.
Otherwise:
-
attrib.
offset+ byteSize(attrib.format) ≤ descriptor.arrayStride.
-
-
attrib.
offsetis a multiple of the minimum of 4 and byteSize(attrib.format). -
attrib.
shaderLocationis < device.[[device]].[[limits]].maxVertexAttributes.
-
-
Arguments:
-
GPUDevicedevice -
GPUVertexStatedescriptor -
GPUPipelineLayoutlayout
Device timeline steps:
-
Let entryPoint be get the entry point(
VERTEX, descriptor). -
Assert entryPoint is not
null. -
All of the requirements in the following steps must be met.
-
validating GPUProgrammableStage(
VERTEX, descriptor, layout, device) must succeed. -
descriptor.
buffers.size must be ≤ device.[[device]].[[limits]].maxVertexBuffers. -
Each vertexBuffer layout descriptor in the list descriptor.
buffersmust pass validating GPUVertexBufferLayout(device, vertexBuffer). -
The sum of vertexBuffer.
attributes.size, over every vertexBuffer in descriptor.buffers, must be ≤ device.[[device]].[[limits]].maxVertexAttributes. -
For every vertex attribute declaration (at location location with type T) that is statically used by entryPoint, there must be exactly one pair (i, j) for which descriptor.
buffers[i]?.attributes[j].shaderLocation== location.Let attrib be that
GPUVertexAttribute. -
T must be compatible with attrib.
format’s vertex data type:- "unorm", "snorm", or "float"
-
T must be
f32orvecN<f32>. - "uint"
-
T must be
u32orvecN<u32>. - "sint"
-
T must be
i32orvecN<i32>.
-
11. Copies
11.1. Buffer Copies
Buffer copy operations operate on raw bytes.
WebGPU provides "buffered" GPUCommandEncoder
commands:
and "immediate" GPUQueue
operations:
-
writeBuffer(), forArrayBuffer-to-GPUBufferwrites
11.2. Texel Copies
Texel copy operations operate on texture/"image" data, rather than bytes.
WebGPU provides "buffered" GPUCommandEncoder
commands:
and "immediate" GPUQueue
operations:
-
writeTexture(), forArrayBuffer-to-GPUTexturewrites -
copyExternalImageToTexture(), for copies from Web Platform image sources to textures
During a texel copy texels are copied over with an equivalent texel representation. Texel copies only guarantee that valid, normal numeric values in the source have the same numeric value in the destination, and may not preserve the bit-representations of the the following values:
-
snorm values may represent -1.0 as either -127 or -128.
-
The signs of zero values may not be preserved.
-
Subnormal floating-point values may be replaced by either -0.0 or +0.0.
-
Any NaN or Infinity is an invalid value and may be replace by an indeterminate value.
Note: Copies may be performed with WGSL shaders, which means that any of the documented WGSL floating point behaviors may be observed.
The following definitions are used by these methods:
11.2.1. GPUTexelCopyBufferLayout
"GPUTexelCopyBufferLayout"
describes the "layout" of texels in a "buffer" of bytes
(GPUBuffer
or AllowSharedBufferSource)
in a "texel copy"
operation.
dictionary GPUTexelCopyBufferLayout {GPUSize64 offset = 0;GPUSize32 bytesPerRow ;GPUSize32 rowsPerImage ; };
A texel image is comprised
of one or more rows of texel
blocks, referred to here
as texel block rows.
Each texel block row of a
texel image must contain the
same number of texel blocks, and
all texel blocks in a texel image are of the same
GPUTextureFormat.
A GPUTexelCopyBufferLayout
is a layout of texel images within
some linear memory.
It’s used when copying data between a texture and a GPUBuffer, or
when scheduling a
write into a texture from the GPUQueue.
-
For
2dtextures, data is copied between one or multiple contiguous texel images and array layers. -
For
3dtextures, data is copied between one or multiple contiguous texel images and depth slices.
Operations that copy between byte arrays and textures always operate on whole texel block. It’s not possible to update only a part of a texel block.
Texel blocks are tightly packed within each texel block row in the linear memory layout of a texel copy, with each subsequent texel block immediately following the previous texel block, with no padding. This includes copies to/from specific aspects of depth-or-stencil format textures: stencil values are tightly packed in an array of bytes; depth values are tightly packed in an array of the appropriate type ("depth16unorm" or "depth32float").
offset, of type GPUSize64, defaulting to0-
The offset, in bytes, from the beginning of the texel data source (such as a
GPUTexelCopyBufferInfo.buffer) to the start of the texel data within that source. bytesPerRow, of type GPUSize32-
The stride, in bytes, between the beginning of each texel block row and the subsequent texel block row.
Required if there are multiple texel block rows (i.e. the copy height or depth is more than one block).
rowsPerImage, of type GPUSize32-
Number of texel block rows per single texel image of the texture.
rowsPerImage×bytesPerRowis the stride, in bytes, between the beginning of each texel image of data and the subsequent texel image.Required if there are multiple texel images (i.e. the copy depth is more than one).
11.2.2. GPUTexelCopyBufferInfo
"GPUTexelCopyBufferInfo"
describes the "info" (GPUBuffer and
GPUTexelCopyBufferLayout)
about a "buffer" source or destination of a "texel copy" operation.
Together with the copySize, it describes the footprint of a region of texels in a GPUBuffer.
dictionary GPUTexelCopyBufferInfo :GPUTexelCopyBufferLayout {required GPUBuffer buffer ; };
buffer, of type GPUBuffer-
A buffer which either contains texel data to be copied or will store the texel data being copied, depending on the method it is being passed to.
Arguments:
-
GPUTexelCopyBufferInfoimageCopyBuffer
Returns: boolean
Device timeline steps:
-
Return
trueif and only if all of the following conditions are satisfied:-
imageCopyBuffer.
bytesPerRowmust be a multiple of 256.
11.2.3. GPUTexelCopyTextureInfo
"GPUTexelCopyTextureInfo"
describes the "info" (GPUTexture,
etc.)
about a "texture" source or destination of a "texel copy" operation.
Together with the copySize, it describes a sub-region of a texture
(spanning one or more contiguous texture subresources at the same mip-map level).
dictionary GPUTexelCopyTextureInfo {required GPUTexture texture ;GPUIntegerCoordinate mipLevel = 0;GPUOrigin3D origin = {};GPUTextureAspect aspect = "all"; };
texture, of type GPUTexture-
Texture to copy to/from.
mipLevel, of type GPUIntegerCoordinate, defaulting to0-
Mip-map level of the
textureto copy to/from. origin, of type GPUOrigin3D, defaulting to{}-
Defines the origin of the copy - the minimum corner of the texture sub-region to copy to/from. Together with
copySize, defines the full copy sub-region. aspect, of type GPUTextureAspect, defaulting to"all"-
Defines which aspects of the
textureto copy to/from.
GPUTexelCopyTextureInfo
copyTexture is determined by running the following steps:
GPUTexelCopyBufferLayout
bufferLayout
corresponding to texel block
x, y of depth slice or array layer z of a GPUTexture
texture is
determined by running the following steps:
-
Let blockBytes be the texel block copy footprint of texture.
format. -
Let imageOffset be (z × bufferLayout.
rowsPerImage× bufferLayout.bytesPerRow) + bufferLayout.offset. -
Let rowOffset be (y × bufferLayout.
bytesPerRow) + imageOffset. -
Let blockOffset be (x × blockBytes) + rowOffset.
-
Return blockOffset.
Arguments:
-
GPUTexelCopyTextureInfotexelCopyTextureInfo -
GPUExtent3DcopySize
Returns: boolean
Device timeline steps:
-
Let blockWidth be the texel block width of texelCopyTextureInfo.
texture.format. -
Let blockHeight be the texel block height of texelCopyTextureInfo.
texture.format. -
Return
trueif and only if all of the following conditions apply:-
validating texture copy range(texelCopyTextureInfo, copySize) returns
true. -
texelCopyTextureInfo.
texturemust be a validGPUTexture. -
texelCopyTextureInfo.
mipLevelmust be < texelCopyTextureInfo.texture.mipLevelCount. -
texelCopyTextureInfo.
origin.x must be a multiple of blockWidth. -
texelCopyTextureInfo.
origin.y must be a multiple of blockHeight. -
The GPUTexelCopyTextureInfo physical subresource size of texelCopyTextureInfo is equal to copySize if either of the following conditions is true:
-
texelCopyTextureInfo.
texture.formatis a depth-stencil format. -
texelCopyTextureInfo.
texture.sampleCount> 1.
-
-
Arguments:
-
GPUTexelCopyTextureInfotexelCopyTextureInfo -
GPUTexelCopyBufferLayoutbufferLayout -
GPUSize64OutdataLength -
GPUExtent3DcopySize -
GPUTextureUsagetextureUsage -
booleanaligned
Returns: boolean
Device timeline steps:
-
Let texture be texelCopyTextureInfo.
texture -
Let aspectSpecificFormat = texture.
format. -
Let offsetAlignment = texel block copy footprint of texture.
format. -
Return
trueif and only if all of the following conditions apply:-
validating GPUTexelCopyTextureInfo(texelCopyTextureInfo, copySize) returns
true. -
texture.
sampleCountis 1. -
texture.
usagecontains textureUsage. -
If texture.
formatis a depth-or-stencil format format:-
texelCopyTextureInfo.
aspectmust refer to a single aspect of texture.format. -
If textureUsage is:
COPY_SRC-
That aspect must be a valid texel copy source according to § 26.1.2 Depth-stencil formats.
COPY_DST-
That aspect must be a valid texel copy destination according to § 26.1.2 Depth-stencil formats.
-
Set aspectSpecificFormat to the aspect-specific format according to § 26.1.2 Depth-stencil formats.
-
Set offsetAlignment to 4.
-
-
If aligned is
true:-
bufferLayout.
offsetis a multiple of offsetAlignment.
-
-
validating linear texture data(bufferLayout, dataLength, aspectSpecificFormat, copySize) succeeds.
-
11.2.4.
GPUCopyExternalImageDestInfo
WebGPU textures hold raw numeric data, and are not tagged with semantic metadata describing colors.
However, copyExternalImageToTexture()
copies from sources that describe colors.
"GPUCopyExternalImageDestInfo"
describes the "info" about the "destination" of a
"copyExternalImageToTexture()" operation.
It is a GPUTexelCopyTextureInfo
which is additionally tagged with
color space/encoding and alpha-premultiplication metadata, so that semantic color data may be
preserved during copies.
This metadata affects only the semantics of the copy operation
operation, not the state or semantics of the destination texture object.
dictionary GPUCopyExternalImageDestInfo :GPUTexelCopyTextureInfo {PredefinedColorSpace colorSpace = "srgb";boolean premultipliedAlpha =false ; };
colorSpace, of type PredefinedColorSpace, defaulting to"srgb"-
Describes the color space and encoding used to encode data into the destination texture.
This may result in values outside of the range [0, 1] being written to the target texture, if its format can represent them. Otherwise, the results are clamped to the target texture format’s range.
Note: If
colorSpacematches the source image, conversion may not be necessary. See § 3.10.2 Color Space Conversion Elision. premultipliedAlpha, of type boolean, defaulting tofalse-
Describes whether the data written into the texture should have its RGB channels premultiplied by the alpha channel, or not.
If this option is set to
trueand thesourceis also premultiplied, the source RGB values must be preserved even if they exceed their corresponding alpha values.Note: If
premultipliedAlphamatches the source image, conversion may not be necessary. See § 3.10.2 Color Space Conversion Elision.
11.2.5.
GPUCopyExternalImageSourceInfo
"GPUCopyExternalImageSourceInfo"
describes the "info" about the "source" of a
"copyExternalImageToTexture()" operation.
typedef (ImageBitmap or ImageData or HTMLImageElement or HTMLVideoElement or VideoFrame or HTMLCanvasElement or OffscreenCanvas );GPUCopyExternalImageSource dictionary GPUCopyExternalImageSourceInfo {required GPUCopyExternalImageSource source ;GPUOrigin2D origin = {};boolean flipY =false ; };
GPUCopyExternalImageSourceInfo
has the following members:
source, of type GPUCopyExternalImageSource-
The source of the texel copy. The copy source data is captured at the moment that
copyExternalImageToTexture()is issued. Source size is determined as described by the external source dimensions table. origin, of type GPUOrigin2D, defaulting to{}-
Defines the origin of the copy - the minimum (top-left) corner of the source sub-region to copy from. Together with
copySize, defines the full copy sub-region. flipY, of type boolean, defaulting tofalse-
Describes whether the source image is vertically flipped, or not.
If this option is set to
true, the copy is flipped vertically: the bottom row of the source region is copied into the first row of the destination region, and so on. Theoriginoption is still relative to the top-left corner of the source image, increasing downward.
When external sources are used when creating or copying to textures, the external source dimensions are defined by the source type, given by this table:
11.2.6. Subroutines
Arguments:
-
GPUTexelCopyTextureInfotexelCopyTextureInfo
Returns: GPUExtent3D
The GPUTexelCopyTextureInfo physical subresource size of texelCopyTextureInfo is calculated as follows:
Its width, height and depthOrArrayLayers are the width, height, and
depth, respectively,
of the physical miplevel-specific texture extent
of texelCopyTextureInfo.texture
subresource at mipmap level
texelCopyTextureInfo.mipLevel.
Arguments:
GPUTexelCopyBufferLayoutlayout-
Layout of the linear texture data.
GPUSize64byteSize-
Total size of the linear data, in bytes.
GPUTextureFormatformat-
Format of the texture.
GPUExtent3DcopyExtent-
Extent of the texture to copy.
Device timeline steps:
-
Let:
-
widthInBlocks be copyExtent.width ÷ the texel block width of format. Assert this is an integer.
-
heightInBlocks be copyExtent.height ÷ the texel block height of format. Assert this is an integer.
-
bytesInLastRow be widthInBlocks × the texel block copy footprint of format.
-
-
Fail if the following input validation requirements are not met:
-
If heightInBlocks > 1, layout.
bytesPerRowmust be specified. -
If copyExtent.depthOrArrayLayers > 1, layout.
bytesPerRowand layout.rowsPerImagemust be specified. -
If specified, layout.
bytesPerRowmust be ≥ bytesInLastRow. -
If specified, layout.
rowsPerImagemust be ≥ heightInBlocks.
-
-
Let:
-
bytesPerRow be layout.
bytesPerRow?? 0. -
rowsPerImage be layout.
rowsPerImage?? 0.
Note: These default values have no effect, as they’re always multiplied by 0.
-
-
Let requiredBytesInCopy be 0.
-
If copyExtent.depthOrArrayLayers > 0:
-
Increment requiredBytesInCopy by bytesPerRow × rowsPerImage × (copyExtent.depthOrArrayLayers − 1).
-
If heightInBlocks > 0:
-
Increment requiredBytesInCopy by bytesPerRow × (heightInBlocks − 1) + bytesInLastRow.
-
-
-
Fail if the following condition is not satisfied:
-
The layout fits inside the linear data: layout.
offset+ requiredBytesInCopy ≤ byteSize.
-
Arguments:
GPUTexelCopyTextureInfotexelCopyTextureInfo-
The texture subresource being copied into and copy origin.
GPUExtent3DcopySize-
The size of the texture.
Device timeline steps:
-
Let blockWidth be the texel block width of texelCopyTextureInfo.
texture.format. -
Let blockHeight be the texel block height of texelCopyTextureInfo.
texture.format. -
Let subresourceSize be the GPUTexelCopyTextureInfo physical subresource size of texelCopyTextureInfo.
-
Return whether all the conditions below are satisfied:
-
(texelCopyTextureInfo.
origin.x + copySize.width) ≤ subresourceSize.width -
(texelCopyTextureInfo.
origin.y + copySize.height) ≤ subresourceSize.height -
(texelCopyTextureInfo.
origin.z + copySize.depthOrArrayLayers) ≤ subresourceSize.depthOrArrayLayers -
copySize.width must be a multiple of blockWidth.
-
copySize.height must be a multiple of blockHeight.
Note: The texture copy range is validated against the physical (rounded-up) size for compressed formats, allowing copies to access texture blocks which are not fully inside the texture.
-
GPUTextureFormats
format1 and format2 are copy-compatible if:
-
format1 equals format2, or
-
format1 and format2 differ only in whether they are
srgbformats (have the-srgbsuffix).
texture
for which each subresource s satisfies the following:
-
The mipmap level of s equals texelCopyTextureInfo.
mipLevel. -
The aspect of s is in the set of aspects of texelCopyTextureInfo.
aspect. -
-
The array layer of s is ≥ texelCopyTextureInfo.
origin.z and < texelCopyTextureInfo.origin.z + copySize.depthOrArrayLayers.
-
12. Command Buffers
Command buffers are pre-recorded lists of GPU commands (blocks of queue timeline
steps) that can be submitted to a GPUQueue for
execution.
Each GPU command
represents a task to be performed on the
queue timeline, such as
setting state, drawing, copying resources, etc.
A GPUCommandBuffer
can only be submitted once, at which point it becomes invalidated.
To reuse rendering commands across multiple submissions, use GPURenderBundle.
12.1. GPUCommandBuffer
[Exposed =(Window ,Worker ),SecureContext ]interface GPUCommandBuffer { };GPUCommandBuffer includes GPUObjectBase ;
GPUCommandBuffer
has the following device timeline properties:
[[command_list]], of type list<GPU command>, readonly-
A list of GPU commands to be executed on the Queue timeline when this command buffer is submitted.
[[renderState]], of type RenderState, initiallynull-
The current state used by any render pass commands being executed.
12.1.1. Command Buffer Creation
dictionary :GPUCommandBufferDescriptor GPUObjectDescriptorBase { };
13. Command Encoding
13.1. GPUCommandsMixin
GPUCommandsMixin
defines state common to all interfaces which encode commands.
It has no methods.
interface mixin GPUCommandsMixin { };
GPUCommandsMixin
has the following device timeline properties:
[[state]], of type encoder state, initially "open"-
The current state of the encoder.
[[commands]], of type list<GPU command>, initially[]-
A list of GPU commands to be executed on the Queue timeline when a
GPUCommandBuffercontaining these commands is submitted.
The encoder state may be one of the following:
- "open"
-
The encoder is available to encode new commands.
- "locked"
-
The encoder cannot be used, because it is locked by a child encoder: it is a
GPUCommandEncoder, and aGPURenderPassEncoderorGPUComputePassEncoderis active. The encoder becomes "open" again when the pass is ended.Any command issued in this state invalidates the encoder.
- "ended"
-
The encoder has been ended and new commands can no longer be encoded.
Any command issued in this state will generate a validation error.
GPUCommandsMixin
encoder run the following device timeline steps:
-
If encoder.
[[state]]is:- "open"
-
Return
true. - "locked"
-
Invalidate encoder and return
false. - "ended"
-
Generate a validation error, and return
false.
GPUCommandsMixin
encoder
which issues the steps of a GPU
Command command, run the following device timeline steps:
-
Append command to encoder.
[[commands]]. -
When command is executed as part of a
GPUCommandBuffer:-
Issue the steps of command.
-
13.2. GPUCommandEncoder
[Exposed =(Window ,Worker ),SecureContext ]interface GPUCommandEncoder {GPURenderPassEncoder beginRenderPass (GPURenderPassDescriptor descriptor );GPUComputePassEncoder beginComputePass (optional GPUComputePassDescriptor descriptor = {});undefined copyBufferToBuffer (GPUBuffer ,source GPUBuffer ,destination optional GPUSize64 );size undefined copyBufferToBuffer (GPUBuffer source ,GPUSize64 sourceOffset ,GPUBuffer destination ,GPUSize64 destinationOffset ,optional GPUSize64 size );undefined copyBufferToTexture (GPUTexelCopyBufferInfo source ,GPUTexelCopyTextureInfo destination ,GPUExtent3D copySize );undefined copyTextureToBuffer (GPUTexelCopyTextureInfo source ,GPUTexelCopyBufferInfo destination ,GPUExtent3D copySize );undefined copyTextureToTexture (GPUTexelCopyTextureInfo source ,GPUTexelCopyTextureInfo destination ,GPUExtent3D copySize );undefined clearBuffer (GPUBuffer buffer ,optional GPUSize64 offset = 0,optional GPUSize64 size );undefined resolveQuerySet (GPUQuerySet querySet ,GPUSize32 firstQuery ,GPUSize32 queryCount ,GPUBuffer destination ,GPUSize64 destinationOffset );GPUCommandBuffer finish (optional GPUCommandBufferDescriptor descriptor = {}); };GPUCommandEncoder includes GPUObjectBase ;GPUCommandEncoder includes GPUCommandsMixin ;GPUCommandEncoder includes GPUDebugCommandsMixin ;
13.2.1. Command Encoder Creation
dictionary :GPUCommandEncoderDescriptor GPUObjectDescriptorBase { };
createCommandEncoder(descriptor)-
Creates a
GPUCommandEncoder.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createCommandEncoder(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUCommandEncoderDescriptor✘ ✔ Description of the GPUCommandEncoderto create.Returns:
GPUCommandEncoderContent timeline steps:
-
Let e be ! create a new WebGPU object(this,
GPUCommandEncoder, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return e.
Device timeline initialization steps:-
If any of the following conditions are unsatisfied generate a validation error, invalidate e and return.
-
this must not be lost.
-
-
GPUCommandEncoder,
encoding a command to clear a buffer, finishing the
encoder to get a GPUCommandBuffer,
then submitting it to the GPUQueue.
const commandEncoder= gpuDevice. createCommandEncoder(); commandEncoder. clearBuffer( buffer); const commandBuffer= commandEncoder. finish(); gpuDevice. queue. submit([ commandBuffer]);
13.3. Pass Encoding
beginRenderPass(descriptor)-
Begins encoding a render pass described by descriptor.
Called on:GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.beginRenderPass(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderPassDescriptor✘ ✘ Description of the GPURenderPassEncoderto create.Returns:
GPURenderPassEncoderContent timeline steps:
-
For each non-
nullcolorAttachment in descriptor.colorAttachments:-
If colorAttachment.
clearValueis provided:-
? validate GPUColor shape(colorAttachment.
clearValue).
-
-
-
Let pass be a new
GPURenderPassEncoderobject. -
Issue the initialization steps on the Device timeline of this.
-
Return pass.
Device timeline initialization steps:-
Validate the encoder state of this. If it returns false, invalidate pass and return.
-
Let attachmentRegions be a list of [texture subresource,
depthSlice?] pairs, initially empty. Each pair describes the region of the texture to be rendered to, which includes a single depth slice for"3d"textures only. -
For each non-
nullcolorAttachment in descriptor.colorAttachments:-
Add [colorAttachment.
view, colorAttachment.depthSlice??null] to attachmentRegions. -
If colorAttachment.
resolveTargetis notnull:-
Add [colorAttachment.
resolveTarget,undefined] to attachmentRegions.
-
-
-
If any of the following requirements are unmet, invalidate pass and return.
-
descriptor must meet the Valid Usage rules given device this.
[[device]]. -
The set of texture regions in attachmentRegions must be pairwise disjoint. That is, no two texture regions may overlap.
-
-
Add each texture subresource in attachmentRegions to pass.
[[usage scope]]with usage attachment. -
Let depthStencilAttachment be descriptor.
depthStencilAttachment. -
If depthStencilAttachment is not
null:-
Let depthStencilView be depthStencilAttachment.
view. -
Add the depth subresource of depthStencilView, if any, to pass.
[[usage scope]]with usage attachment-read if depthStencilAttachment.depthReadOnlyis true, or attachment otherwise. -
Add the stencil subresource of depthStencilView, if any, to pass.
[[usage scope]]with usage attachment-read if depthStencilAttachment.stencilReadOnlyis true, or attachment otherwise. -
Set pass.
[[depthReadOnly]]to depthStencilAttachment.depthReadOnly. -
Set pass.
[[stencilReadOnly]]to depthStencilAttachment.stencilReadOnly.
-
-
Set pass.
[[layout]]to derive render targets layout from pass(descriptor). -
If descriptor.
timestampWritesis provided:-
Let timestampWrites be descriptor.
timestampWrites. -
If timestampWrites.
beginningOfPassWriteIndexis provided, append a GPU command to this.[[commands]]with the following steps:-
Before the pass commands begin executing, write the current queue timestamp into index timestampWrites.
beginningOfPassWriteIndexof timestampWrites.querySet.
-
-
If timestampWrites.
endOfPassWriteIndexis provided, set pass.[[endTimestampWrite]]to a GPU command with the following steps:-
After the pass commands finish executing, write the current queue timestamp into index timestampWrites.
endOfPassWriteIndexof timestampWrites.querySet.
-
-
-
Set pass.
[[drawCount]]to 0. -
Set pass.
[[maxDrawCount]]to descriptor.maxDrawCount. -
Set pass.
[[maxDrawCount]]to descriptor.maxDrawCount. -
Enqueue a command on this which issues the subsequent steps on the Queue timeline when executed.
Queue timeline steps:-
Let the
[[renderState]]of the currently executingGPUCommandBufferbe a new RenderState. -
Set
[[renderState]].[[colorAttachments]]to descriptor.colorAttachments. -
Set
[[renderState]].[[depthStencilAttachment]]to descriptor.depthStencilAttachment. -
For each non-
nullcolorAttachment in descriptor.colorAttachments:-
Let colorView be colorAttachment.
view. -
If colorView.
[[descriptor]].dimensionis:"3d"-
Let colorSubregion be colorAttachment.
depthSliceof colorView. - Otherwise
-
Let colorSubregion be colorView.
-
If colorAttachment.
loadOpis:"load"-
Ensure the contents of colorSubregion are loaded into the framebuffer memory associated with colorSubregion.
"clear"-
Set every texel of the framebuffer memory associated with colorSubregion to colorAttachment.
clearValue.
-
-
If depthStencilAttachment is not
null:-
If depthStencilAttachment.
depthLoadOpis:- Not provided
-
Assert that depthStencilAttachment.
depthReadOnlyistrueand ensure the contents of the depth subresource of depthStencilView are loaded into the framebuffer memory associated with depthStencilView. "load"-
Ensure the contents of the depth subresource of depthStencilView are loaded into the framebuffer memory associated with depthStencilView.
"clear"-
Set every texel of the framebuffer memory associated with the depth subresource of depthStencilView to depthStencilAttachment.
depthClearValue.
-
If depthStencilAttachment.
stencilLoadOpis:- Not provided
-
Assert that depthStencilAttachment.
stencilReadOnlyistrueand ensure the contents of the stencil subresource of depthStencilView are loaded into the framebuffer memory associated with depthStencilView. "load"-
Ensure the contents of the stencil subresource of depthStencilView are loaded into the framebuffer memory associated with depthStencilView.
"clear"-
Set every texel of the framebuffer memory associated with the stencil subresource depthStencilView to depthStencilAttachment.
stencilClearValue.
-
Note: Read-only depth-stencil attachments are implicitly treated as though the
"load"operation was used. Validation that requires the load op to not be provided for read-only attachments is done in GPURenderPassDepthStencilAttachment Valid Usage. -
beginComputePass(descriptor)-
Begins encoding a compute pass described by descriptor.
Called on:GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.beginComputePass(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUComputePassDescriptor✘ ✔ Returns:
GPUComputePassEncoderContent timeline steps:
-
Let pass be a new
GPUComputePassEncoderobject. -
Issue the initialization steps on the Device timeline of this.
-
Return pass.
Device timeline initialization steps:-
Validate the encoder state of this. If it returns false, invalidate pass and return.
-
If any of the following requirements are unmet, invalidate pass and return.
-
If descriptor.
timestampWritesis provided:-
Validate timestampWrites(this.
[[device]], descriptor.timestampWrites) must return true.
-
-
-
If descriptor.
timestampWritesis provided:-
Let timestampWrites be descriptor.
timestampWrites. -
If timestampWrites.
beginningOfPassWriteIndexis provided, append a GPU command to this.[[commands]]with the following steps:-
Before the pass commands begin executing, write the current queue timestamp into index timestampWrites.
beginningOfPassWriteIndexof timestampWrites.querySet.
-
-
If timestampWrites.
endOfPassWriteIndexis provided, set pass.[[endTimestampWrite]]to a GPU command with the following steps:-
After the pass commands finish executing, write the current queue timestamp into index timestampWrites.
endOfPassWriteIndexof timestampWrites.querySet.
-
-
-
13.4. Buffer Copy Commands
copyBufferToBuffer() has two overloads:
copyBufferToBuffer(source, destination, size)-
Shorthand, equivalent to
copyBufferToBuffer(source, 0, destination, 0, size). copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size)-
Encode a command into the
GPUCommandEncoderthat copies data from a sub-region of aGPUBufferto a sub-region of anotherGPUBuffer.Called on:GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size) method. Parameter Type Nullable Optional Description sourceGPUBuffer✘ ✘ The GPUBufferto copy from.sourceOffsetGPUSize64✘ ✘ Offset in bytes into source to begin copying from. destinationGPUBuffer✘ ✘ The GPUBufferto copy to.destinationOffsetGPUSize64✘ ✘ Offset in bytes into destination to place the copied data. sizeGPUSize64✘ ✔ Bytes to copy. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If size is
undefined, set it to source.size− sourceOffset. -
If any of the following conditions are unsatisfied, invalidate this and return.
-
source is valid to use with this.
-
destination is valid to use with this.
-
size is a multiple of 4.
-
sourceOffset is a multiple of 4.
-
destinationOffset is a multiple of 4.
-
source.
size≥ (sourceOffset + size). -
destination.
size≥ (destinationOffset + size). -
source and destination are not the same
GPUBuffer.
-
-
Enqueue a command on this which issues the subsequent steps on the Queue timeline when executed.
Queue timeline steps:-
Copy size bytes of source, beginning at sourceOffset, into destination, beginning at destinationOffset.
-
clearBuffer(buffer, offset, size)-
Encode a command into the
GPUCommandEncoderthat fills a sub-region of aGPUBufferwith zeros.Called on:GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.clearBuffer(buffer, offset, size) method. Parameter Type Nullable Optional Description bufferGPUBuffer✘ ✘ The GPUBufferto clear.offsetGPUSize64✘ ✔ Offset in bytes into buffer where the sub-region to clear begins. sizeGPUSize64✘ ✔ Size in bytes of the sub-region to clear. Defaults to the size of the buffer minus offset. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If size is missing, set size to
max(0, buffer..size- offset) -
If any of the following conditions are unsatisfied, invalidate this and return.
-
buffer is valid to use with this.
-
size is a multiple of 4.
-
offset is a multiple of 4.
-
buffer.
size≥ (offset + size).
-
-
Enqueue a command on this which issues the subsequent steps on the Queue timeline when executed.
Queue timeline steps:-
Set size bytes of buffer to
0starting at offset.
-
13.5. Texel Copy Commands
copyBufferToTexture(source, destination, copySize)-
Encode a command into the
GPUCommandEncoderthat copies data from a sub-region of aGPUBufferto a sub-region of one or multiple continuous texture subresources.Called on:GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.copyBufferToTexture(source, destination, copySize) method. Parameter Type Nullable Optional Description sourceGPUTexelCopyBufferInfo✘ ✘ Combined with copySize, defines the region of the source buffer. destinationGPUTexelCopyTextureInfo✘ ✘ Combined with copySize, defines the region of the destination texture subresource. copySizeGPUExtent3D✘ ✘ Returns:
undefinedContent timeline steps:
-
? validate GPUOrigin3D shape(destination.
origin). -
? validate GPUExtent3D shape(copySize).
-
Issue the subsequent steps on the Device timeline of this.
[[device]]:
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let aligned be
true. -
If any of the following conditions are unsatisfied, invalidate this and return.
-
validating GPUTexelCopyBufferInfo(source) returns
true. -
validating texture buffer copy(destination, source, dataLength, copySize,
COPY_DST, aligned) returnstrue.
-
-
Enqueue a command on this which issues the subsequent steps on the Queue timeline when executed.
Queue timeline steps:-
Let blockWidth be the texel block width of destination.
texture. -
Let blockHeight be the texel block height of destination.
texture. -
Let dstOrigin be destination.
origin. -
Let dstBlockOriginX be (dstOrigin.x ÷ blockWidth).
-
Let dstBlockOriginY be (dstOrigin.y ÷ blockHeight).
-
Let blockColumns be (copySize.width ÷ blockWidth).
-
Let blockRows be (copySize.height ÷ blockHeight).
-
Assert that dstBlockOriginX, dstBlockOriginY, blockColumns, and blockRows are integers.
-
For each z in the range [0, copySize.depthOrArrayLayers − 1]:
-
Let dstSubregion be texture copy sub-region (z + dstOrigin.z) of destination.
-
For each y in the range [0, blockRows − 1]:
-
For each x in the range [0, blockColumns − 1]:
-
Let blockOffset be the texel block byte offset of source for (x, y, z) of destination.
texture. -
Set texel block (dstBlockOriginX + x, dstBlockOriginY + y) of dstSubregion to be an equivalent texel representation to the texel block described by source.
bufferat offset blockOffset.
-
-
-
-
copyTextureToBuffer(source, destination, copySize)-
Encode a command into the
GPUCommandEncoderthat copies data from a sub-region of one or multiple continuous texture subresources to a sub-region of aGPUBuffer.Called on:GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.copyTextureToBuffer(source, destination, copySize) method. Parameter Type Nullable Optional Description sourceGPUTexelCopyTextureInfo✘ ✘ Combined with copySize, defines the region of the source texture subresources. destinationGPUTexelCopyBufferInfo✘ ✘ Combined with copySize, defines the region of the destination buffer. copySizeGPUExtent3D✘ ✘ Returns:
undefinedContent timeline steps:
-
? validate GPUOrigin3D shape(source.
origin). -
? validate GPUExtent3D shape(copySize).
-
Issue the subsequent steps on the Device timeline of this.
[[device]]:
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let aligned be
true. -
If any of the following conditions are unsatisfied, invalidate this and return.
-
validating GPUTexelCopyBufferInfo(destination) returns
true. -
validating texture buffer copy(source, destination, dataLength, copySize,
COPY_SRC, aligned) returnstrue.
-
-
Enqueue a command on this which issues the subsequent steps on the Queue timeline when executed.
Queue timeline steps:-
Let blockWidth be the texel block width of source.
texture. -
Let blockHeight be the texel block height of source.
texture. -
Let srcOrigin be source.
origin. -
Let srcBlockOriginX be (srcOrigin.x ÷ blockWidth).
-
Let srcBlockOriginY be (srcOrigin.y ÷ blockHeight).
-
Let blockColumns be (copySize.width ÷ blockWidth).
-
Let blockRows be (copySize.height ÷ blockHeight).
-
Assert that srcBlockOriginX, srcBlockOriginY, blockColumns, and blockRows are integers.
-
For each z in the range [0, copySize.depthOrArrayLayers − 1]:
-
Let srcSubregion be texture copy sub-region (z + srcOrigin.z) of source.
-
For each y in the range [0, blockRows − 1]:
-
For each x in the range [0, blockColumns − 1]:
-
Let blockOffset be the texel block byte offset of destination for (x, y, z) of source.
texture. -
Set destination.
bufferat offset blockOffset to be an equivalent texel representation to texel block (srcBlockOriginX + x, srcBlockOriginY + y) of srcSubregion.
-
-
-
-
copyTextureToTexture(source, destination, copySize)-
Encode a command into the
GPUCommandEncoderthat copies data from a sub-region of one or multiple contiguous texture subresources to another sub-region of one or multiple continuous texture subresources.Called on:GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.copyTextureToTexture(source, destination, copySize) method. Parameter Type Nullable Optional Description sourceGPUTexelCopyTextureInfo✘ ✘ Combined with copySize, defines the region of the source texture subresources. destinationGPUTexelCopyTextureInfo✘ ✘ Combined with copySize, defines the region of the destination texture subresources. copySizeGPUExtent3D✘ ✘ Returns:
undefinedContent timeline steps:
-
? validate GPUOrigin3D shape(source.
origin). -
? validate GPUOrigin3D shape(destination.
origin). -
? validate GPUExtent3D shape(copySize).
-
Issue the subsequent steps on the Device timeline of this.
[[device]]:
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
Let srcTexture be source.
texture. -
Let dstTexture be destination.
texture. -
validating GPUTexelCopyTextureInfo(source, copySize) returns
true. -
validating GPUTexelCopyTextureInfo(destination, copySize) returns
true. -
srcTexture.
sampleCountis equal to dstTexture.sampleCount. -
srcTexture.
formatand dstTexture.formatmust be copy-compatible. -
If srcTexture.
formatis a depth-stencil format: -
The set of subresources for texture copy(source, copySize) and the set of subresources for texture copy(destination, copySize) are disjoint.
-
-
Enqueue a command on this which issues the subsequent steps on the Queue timeline when executed.
Queue timeline steps:-
Let blockWidth be the texel block width of source.
texture. -
Let blockHeight be the texel block height of source.
texture. -
Let srcOrigin be source.
origin. -
Let srcBlockOriginX be (srcOrigin.x ÷ blockWidth).
-
Let srcBlockOriginY be (srcOrigin.y ÷ blockHeight).
-
Let dstOrigin be destination.
origin. -
Let dstBlockOriginX be (dstOrigin.x ÷ blockWidth).
-
Let dstBlockOriginY be (dstOrigin.y ÷ blockHeight).
-
Let blockColumns be (copySize.width ÷ blockWidth).
-
Let blockRows be (copySize.height ÷ blockHeight).
-
Assert that srcBlockOriginX, srcBlockOriginY, dstBlockOriginX, dstBlockOriginY, blockColumns, and blockRows are integers.
-
For each z in the range [0, copySize.depthOrArrayLayers − 1]:
-
Let srcSubregion be texture copy sub-region (z + srcOrigin.z) of source.
-
Let dstSubregion be texture copy sub-region (z + dstOrigin.z) of destination.
-
For each y in the range [0, blockRows − 1]:
-
For each x in the range [0, blockColumns − 1]:
-
Set texel block (dstBlockOriginX + x, dstBlockOriginY + y) of dstSubregion to be an equivalent texel representation to texel block (srcBlockOriginX + x, srcBlockOriginY + y) of srcSubregion.
-
-
-
-
13.6. Queries
resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset)-
Resolves query results from a
GPUQuerySetout into a range of aGPUBuffer.Called on:GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset) method. Parameter Type Nullable Optional Description querySetGPUQuerySet✘ ✘ firstQueryGPUSize32✘ ✘ queryCountGPUSize32✘ ✘ destinationGPUBuffer✘ ✘ destinationOffsetGPUSize64✘ ✘ Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
querySet is valid to use with this.
-
destination is valid to use with this.
-
destination.
usagecontainsQUERY_RESOLVE. -
firstQuery < the number of queries in querySet.
-
(firstQuery + queryCount) ≤ the number of queries in querySet.
-
destinationOffset is a multiple of 256.
-
destinationOffset + 8 × queryCount ≤ destination.
size.
-
-
Enqueue a command on this which issues the subsequent steps on the Queue timeline when executed.
Queue timeline steps:-
Let queryIndex be firstQuery.
-
Let offset be destinationOffset.
-
While queryIndex < firstQuery + queryCount:
-
Set 8 bytes of destination, beginning at offset, to be the value of querySet at queryIndex.
-
Set queryIndex to be queryIndex + 1.
-
Set offset to be offset + 8.
-
-
13.7. Finalization
A GPUCommandBuffer
containing the commands recorded by the GPUCommandEncoder
can be created
by calling finish().
Once finish()
has been called the
command encoder can no longer be used.
finish(descriptor)-
Completes recording of the commands sequence and returns a corresponding
GPUCommandBuffer.Called on:GPUCommandEncoderthis.Arguments:
Arguments for the GPUCommandEncoder.finish(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUCommandBufferDescriptor✘ ✔ Returns:
GPUCommandBufferContent timeline steps:
-
Let commandBuffer be a new
GPUCommandBuffer. -
Issue the finish steps on the Device timeline of this.
[[device]]. -
Return commandBuffer.
Device timeline finish steps:-
Let validationSucceeded be
trueif all of the following requirements are met, andfalseotherwise.-
this must be valid.
-
this.
[[debug_group_stack]]must be empty.
-
-
If validationSucceeded is
false, then:-
Return an invalidated
GPUCommandBuffer.
-
Set commandBuffer.
[[command_list]]to this.[[commands]].
-
14. Programmable Passes
interface mixin {GPUBindingCommandsMixin undefined setBindGroup (GPUIndex32 index ,GPUBindGroup ?bindGroup ,optional sequence <GPUBufferDynamicOffset >dynamicOffsets = []);undefined setBindGroup (GPUIndex32 index ,GPUBindGroup ?bindGroup , [AllowShared ]Uint32Array dynamicOffsetsData ,GPUSize64 dynamicOffsetsDataStart ,GPUSize32 dynamicOffsetsDataLength ); };
GPUBindingCommandsMixin
assumes the presence of
GPUObjectBase
and GPUCommandsMixin
members on the same object.
It must only be included by interfaces which also include those mixins.
GPUBindingCommandsMixin
has the following device timeline properties:
[[bind_groups]], of type ordered map<GPUIndex32,GPUBindGroup>, initially empty-
The current
GPUBindGroupfor each index. [[dynamic_offsets]], of type ordered map<GPUIndex32, list<GPUBufferDynamicOffset>>, initally empty-
The current dynamic offsets for each
[[bind_groups]]entry.
14.1. Bind Groups
setBindGroup() has two overloads:
setBindGroup(index, bindGroup, dynamicOffsets)-
Sets the current
GPUBindGroupfor the given index.Called on:GPUBindingCommandsMixinthis.Arguments:
index, of typeGPUIndex32, non-nullable, required-
The index to set the bind group at.
bindGroup, of typeGPUBindGroup, nullable, required-
Bind group to use for subsequent render or compute commands.
dynamicOffsets, of type sequence<GPUBufferDynamicOffset>, non-nullable, defaulting to[]-
Array containing buffer offsets in bytes for each entry in bindGroup marked as
buffer.hasDynamicOffset, ordered byGPUBindGroupLayoutEntry.binding. See note for additional details.
Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let dynamicOffsetCount be 0 if
bindGroupisnull, or bindGroup.[[layout]].[[dynamicOffsetCount]]if not. -
If any of the following requirements are unmet, invalidate this and return.
-
index must be < this.
[[device]].[[limits]].maxBindGroups. -
dynamicOffsets.size must equal dynamicOffsetCount.
-
-
If bindGroup is
null:-
Remove this.
[[bind_groups]][index]. -
Remove this.
[[dynamic_offsets]][index].
Otherwise:
-
If any of the following requirements are unmet, invalidate this and return.
-
bindGroup must be valid to use with this.
-
For each dynamic binding (bufferBinding, bufferLayout, dynamicOffsetIndex) in bindGroup:
-
bufferBinding.
offset+ dynamicOffsets[dynamicOffsetIndex] + bufferLayout.minBindingSizemust be ≤ bufferBinding.buffer.size. -
If bufferLayout.
typeis"uniform":-
dynamicOffset must be a multiple of
minUniformBufferOffsetAlignment.
-
-
If bufferLayout.
typeis"storage"or"read-only-storage":-
dynamicOffset must be a multiple of
minStorageBufferOffsetAlignment.
-
-
-
-
Set this.
[[bind_groups]][index] to be bindGroup. -
Set this.
[[dynamic_offsets]][index] to be a copy of dynamicOffsets. -
If this is a
GPURenderCommandsMixin:-
For each bindGroup in this.
[[bind_groups]], merge bindGroup.[[usedResources]]into this.[[usage scope]]
-
-
setBindGroup(index, bindGroup, dynamicOffsetsData, dynamicOffsetsDataStart, dynamicOffsetsDataLength)-
Sets the current
GPUBindGroupfor the given index, specifying dynamic offsets as a subset of aUint32Array.Called on:GPUBindingCommandsMixinthis.Arguments:
Arguments for the GPUBindingCommandsMixin.setBindGroup(index, bindGroup, dynamicOffsetsData, dynamicOffsetsDataStart, dynamicOffsetsDataLength) method. Parameter Type Nullable Optional Description indexGPUIndex32✘ ✘ The index to set the bind group at. bindGroupGPUBindGroup?✔ ✘ Bind group to use for subsequent render or compute commands. dynamicOffsetsDataUint32Array✘ ✘ Array containing buffer offsets in bytes for each entry in bindGroup marked as buffer.hasDynamicOffset, ordered byGPUBindGroupLayoutEntry.binding. See note for additional details.dynamicOffsetsDataStartGPUSize64✘ ✘ Offset in elements into dynamicOffsetsData where the buffer offset data begins. dynamicOffsetsDataLengthGPUSize32✘ ✘ Number of buffer offsets to read from dynamicOffsetsData. Returns:
undefinedContent timeline steps:
-
If any of the following requirements are unmet, throw a
RangeErrorand return.-
dynamicOffsetsDataStart must be ≥ 0.
-
dynamicOffsetsDataStart + dynamicOffsetsDataLength must be ≤ dynamicOffsetsData.
length.
-
-
Let dynamicOffsets be a list containing the range, starting at index dynamicOffsetsDataStart, of dynamicOffsetsDataLength elements of a copy of dynamicOffsetsData.
-
Call this.
setBindGroup(index, bindGroup, dynamicOffsets).
-
GPUBindGroupLayoutEntry.binding
order.
This means that if dynamic bindings is the list of each GPUBindGroupLayoutEntry
in the GPUBindGroupLayout
with buffer?.hasDynamicOffset
set to true, sorted by
GPUBindGroupLayoutEntry.binding,
then dynamic offset[i], as supplied to
setBindGroup(), will correspond to
dynamic bindings[i].
GPUBindGroupLayout
created with the following call:
// Note the bindings are listed out-of-order in this array, but it // doesn’t matter because they will be sorted by binding index. let layout= gpuDevice. createBindGroupLayout({ entries: [{ binding: 1 , buffer: {}, }, { binding: 2 , buffer: { dynamicOffset: true }, }, { binding: 0 , buffer: { dynamicOffset: true }, }] });
Used by a GPUBindGroup
created with the following call:
// Like above, the array order doesn’t matter here. // It doesn’t even need to match the order used in the layout. let bindGroup= gpuDevice. createBindGroup({ layout: layout, entries: [{ binding: 1 , resource: { buffer: bufferA, offset: 256 }, }, { binding: 2 , resource: { buffer: bufferB, offset: 512 }, }, { binding: 0 , resource: { buffer: bufferC}, }] });
And bound with the following call:
pass. setBindGroup( 0 , bindGroup, [ 1024 , 2048 ]);
The following buffer offsets will be applied:
| Binding | Buffer | Offset |
|---|---|---|
| 0 | bufferC | 1024 (Dynamic) |
| 1 | bufferA | 256 (Static) |
| 2 | bufferB | 2560 (Static + Dynamic) |
GPUBindGroup
bindGroup
with a given list of steps to be executed for each dynamic offset, run the following device timeline steps:
-
Let dynamicOffsetIndex be
0. -
Let layout be bindGroup.
[[layout]]. -
For each
GPUBindGroupEntryentry in bindGroup.[[entries]]ordered in increasing values of entry.binding:-
Let bindingDescriptor be the
GPUBindGroupLayoutEntryat layout.[[entryMap]][entry.binding]: -
If bindingDescriptor.
buffer?.hasDynamicOffsetistrue:-
Let bufferBinding be get as buffer binding(entry.
resource). -
Let bufferLayout be bindingDescriptor.
buffer. -
Call steps with bufferBinding, bufferLayout, and dynamicOffsetIndex.
-
Let dynamicOffsetIndex be dynamicOffsetIndex +
1
-
-
Arguments:
GPUBindingCommandsMixinencoder-
Encoder whose bind groups are being validated.
GPUPipelineBasepipeline-
Pipeline to validate encoders bind groups are compatible with.
Device timeline steps:
-
If any of the following conditions are unsatisfied, return
false:-
pipeline must not be
null. -
All bind groups used by the pipeline must be set and compatible with the pipeline layout: For each pair of (
GPUIndex32index,GPUBindGroupLayoutbindGroupLayout) in pipeline.[[layout]].[[bindGroupLayouts]]:-
If bindGroupLayout is
null, continue. -
Let bindGroup be encoder.
[[bind_groups]][index]. -
Let dynamicOffsets be encoder.
[[dynamic_offsets]][index]. -
bindGroup must not be
null. -
bindGroup.
[[layout]]must be group-equivalent with bindGroupLayout. -
Let dynamicOffsetIndex be 0.
-
For each
GPUBindGroupEntrybindGroupEntry in bindGroup.[[entries]], sorted by bindGroupEntry.binding:-
Let bindGroupLayoutEntry be bindGroup.
[[layout]].[[entryMap]][bindGroupEntry.binding]. -
Let bound be get as buffer binding(bindGroupEntry.
resource). -
If bindGroupLayoutEntry.
buffer.hasDynamicOffset:-
Increment bound.
offsetby dynamicOffsets[dynamicOffsetIndex]. -
Increment dynamicOffsetIndex by 1.
-
-
If bindGroupEntry.
[[prevalidatedSize]]isfalse:-
effective buffer binding size(bound) must be ≥ minimum buffer binding size of the binding variable in pipeline’s shader that corresponds to bindGroupEntry.
-
-
-
-
Encoder bind groups alias a writable resource(encoder, pipeline) must be
false.
-
Otherwise return true.
GPUTextureView
object).
Note: This algorithm limits the use of the usage scope storage exception.
Arguments:
GPUBindingCommandsMixinencoder-
Encoder whose bind groups are being validated.
GPUPipelineBasepipeline-
Pipeline to validate encoders bind groups are compatible with.
Device timeline steps:
-
For each stage in [
VERTEX,FRAGMENT,COMPUTE]:-
Let bufferBindings be a list of (
GPUBufferBinding,boolean) pairs, where the latter indicates whether the resource was used as writable. -
Let textureViews be a list of (
GPUTextureView,boolean) pairs, where the latter indicates whether the resource was used as writable. -
For each pair of (
GPUIndex32bindGroupIndex,GPUBindGroupLayoutbindGroupLayout) in pipeline.[[layout]].[[bindGroupLayouts]]:-
Let bindGroup be encoder.
[[bind_groups]][bindGroupIndex]. -
Let bindGroupLayoutEntries be bindGroupLayout.
[[descriptor]].entries. -
Let bufferRanges be the bound buffer ranges of bindGroup, given dynamic offsets encoder.
[[dynamic_offsets]][bindGroupIndex] -
For each (
GPUBindGroupLayoutEntrybindGroupLayoutEntry,GPUBufferBindingresource) in bufferRanges, in which bindGroupLayoutEntry.visibilitycontains stage:-
Let resourceWritable be (bindGroupLayoutEntry.
buffer.type=="storage"). -
For each pair (
GPUBufferBindingpastResource,booleanpastResourceWritable) in bufferBindings:-
If (resourceWritable or pastResourceWritable) is true, and pastResource and resource are buffer-binding-aliasing, return
true.
-
-
Append (resource, resourceWritable) to bufferBindings.
-
-
For each
GPUBindGroupLayoutEntrybindGroupLayoutEntry in bindGroupLayoutEntries, and correspondingGPUTextureViewresource in bindGroup, in which bindGroupLayoutEntry.visibilitycontains stage:-
If bindGroupLayoutEntry.
storageTextureis not provided, continue. -
Let resourceWritable be whether bindGroupLayoutEntry.
storageTexture.accessis a writable access mode. -
For each pair (
GPUTextureViewpastResource,booleanpastResourceWritable) in textureViews,-
If (resourceWritable or pastResourceWritable) is true, and pastResource and resource is texture-view-aliasing, return
true.
-
-
Append (resource, resourceWritable) to textureViews.
-
-
-
-
Return
false.
Note: Implementations are strongly encouraged to optimize this algorithm.
15. Debug Markers
GPUDebugCommandsMixin provides methods to apply debug
labels to groups
of commands or insert a single label into the command sequence.
Debug groups can be nested to create a hierarchy of labeled commands, and must be well-balanced.
Like object labels,
these labels have no required behavior, but may be shown
in error messages and browser developer tools, and may be passed to native API backends.
interface mixin GPUDebugCommandsMixin {undefined pushDebugGroup (USVString groupLabel );undefined popDebugGroup ();undefined insertDebugMarker (USVString markerLabel ); };
GPUDebugCommandsMixin
assumes the presence of
GPUObjectBase
and GPUCommandsMixin
members on the same object.
It must only be included by interfaces which also include those mixins.
GPUDebugCommandsMixin
has the following device timeline properties:
[[debug_group_stack]], of type stack<USVString>-
A stack of active debug group labels.
GPUDebugCommandsMixin
has the following methods:
pushDebugGroup(groupLabel)-
Begins a labeled debug group containing subsequent commands.
Called on:GPUDebugCommandsMixinthis.Arguments:
Arguments for the GPUDebugCommandsMixin.pushDebugGroup(groupLabel) method. Parameter Type Nullable Optional Description groupLabelUSVString✘ ✘ The label for the command group. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Push groupLabel onto this.
[[debug_group_stack]].
-
popDebugGroup()-
Ends the labeled debug group most recently started by
pushDebugGroup().Called on:GPUDebugCommandsMixinthis.Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following requirements are unmet, invalidate this and return.
-
this.
[[debug_group_stack]]must not be empty.
-
-
Pop an entry off of this.
[[debug_group_stack]].
-
insertDebugMarker(markerLabel)-
Marks a point in a stream of commands with a label.
Called on:GPUDebugCommandsMixinthis.Arguments:
Arguments for the GPUDebugCommandsMixin.insertDebugMarker(markerLabel) method. Parameter Type Nullable Optional Description markerLabelUSVString✘ ✘ The label to insert. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
16. Compute Passes
16.1. GPUComputePassEncoder
[Exposed =(Window ,Worker ),SecureContext ]interface GPUComputePassEncoder {undefined setPipeline (GPUComputePipeline pipeline );undefined dispatchWorkgroups (GPUSize32 workgroupCountX ,optional GPUSize32 workgroupCountY = 1,optional GPUSize32 workgroupCountZ = 1);undefined dispatchWorkgroupsIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset );undefined end (); };GPUComputePassEncoder includes GPUObjectBase ;GPUComputePassEncoder includes GPUCommandsMixin ;GPUComputePassEncoder includes GPUDebugCommandsMixin ;GPUComputePassEncoder includes GPUBindingCommandsMixin ;
GPUComputePassEncoder
has the following device timeline properties:
[[command_encoder]], of typeGPUCommandEncoder, readonly-
The
GPUCommandEncoderthat created this compute pass encoder. [[endTimestampWrite]], of type GPU command?, readonly, defaulting tonull-
GPU command, if any, writing a timestamp when the pass ends.
[[pipeline]], of typeGPUComputePipeline, initiallynull-
The current
GPUComputePipeline.
16.1.1. Compute Pass Encoder Creation
dictionary {GPUComputePassTimestampWrites required GPUQuerySet querySet ;GPUSize32 beginningOfPassWriteIndex ;GPUSize32 endOfPassWriteIndex ; };
querySet, of type GPUQuerySet-
The
GPUQuerySet, of type"timestamp", that the query results will be written to. beginningOfPassWriteIndex, of type GPUSize32-
If defined, indicates the query index in
querySetinto which the timestamp at the beginning of the compute pass will be written. endOfPassWriteIndex, of type GPUSize32-
If defined, indicates the query index in
querySetinto which the timestamp at the end of the compute pass will be written.
Note: Timestamp query values are written in nanoseconds, but how the value is determined is implementation-defined and may not increase monotonically. See § 20.4 Timestamp Query for details.
dictionary :GPUComputePassDescriptor GPUObjectDescriptorBase {GPUComputePassTimestampWrites timestampWrites ; };
timestampWrites, of type GPUComputePassTimestampWrites-
Defines which timestamp values will be written for this pass, and where to write them to.
16.1.2. Dispatch
setPipeline(pipeline)-
Sets the current
GPUComputePipeline.Called on:GPUComputePassEncoderthis.Arguments:
Arguments for the GPUComputePassEncoder.setPipeline(pipeline) method. Parameter Type Nullable Optional Description pipelineGPUComputePipeline✘ ✘ The compute pipeline to use for subsequent dispatch commands. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
pipeline is valid to use with this.
-
-
Set this.
[[pipeline]]to be pipeline.
-
dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ)-
Dispatch work to be performed with the current
GPUComputePipeline. See § 23.1 Computing for the detailed specification.Called on:GPUComputePassEncoderthis.Arguments:
Arguments for the GPUComputePassEncoder.dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ) method. Parameter Type Nullable Optional Description workgroupCountXGPUSize32✘ ✘ X dimension of the grid of workgroups to dispatch. workgroupCountYGPUSize32✘ ✔ Y dimension of the grid of workgroups to dispatch. workgroupCountZGPUSize32✘ ✔ Z dimension of the grid of workgroups to dispatch. NOTE:Thex,y, andzvalues passed todispatchWorkgroups()anddispatchWorkgroupsIndirect()are the number of workgroups to dispatch for each dimension, not the number of shader invocations to perform across each dimension. This matches the behavior of modern native GPU APIs, but differs from the behavior of OpenCL.This means that if a
GPUShaderModuledefines an entry point with@workgroup_size(4, 4), and work is dispatched to it with the callcomputePass.dispatchWorkgroups(8, 8);the entry point will be invoked 1024 times total: Dispatching a 4x4 workgroup 8 times along both the X and Y axes. (4*4*8*8=1024)Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let usageScope be an empty usage scope.
-
For each bindGroup in this.
[[bind_groups]], merge bindGroup.[[usedResources]]into this.[[usage scope]] -
If any of the following conditions are unsatisfied, invalidate this and return.
-
usageScope must satisfy usage scope validation.
-
Validate encoder bind groups(this, this.
[[pipeline]]) istrue. -
all of workgroupCountX, workgroupCountY and workgroupCountZ are ≤ this.device.limits.
maxComputeWorkgroupsPerDimension.
-
-
Let bindingState be a snapshot of this’s current state.
-
Enqueue a command on this which issues the subsequent steps on the Queue timeline.
Queue timeline steps:-
Execute a grid of workgroups with dimensions [workgroupCountX, workgroupCountY, workgroupCountZ] with bindingState.
[[pipeline]]using bindingState.[[bind_groups]].
-
dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset)-
Dispatch work to be performed with the current
GPUComputePipelineusing parameters read from aGPUBuffer. See § 23.1 Computing for the detailed specification.The indirect dispatch parameters encoded in the buffer must be a tightly packed block of three 32-bit unsigned integer values (12 bytes total), given in the same order as the arguments for
dispatchWorkgroups(). For example:let dispatchIndirectParameters= new Uint32Array( 3 ); dispatchIndirectParameters[ 0 ] = workgroupCountX; dispatchIndirectParameters[ 1 ] = workgroupCountY; dispatchIndirectParameters[ 2 ] = workgroupCountZ; Called on:GPUComputePassEncoderthis.Arguments:
Arguments for the GPUComputePassEncoder.dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset) method. Parameter Type Nullable Optional Description indirectBufferGPUBuffer✘ ✘ Buffer containing the indirect dispatch parameters. indirectOffsetGPUSize64✘ ✘ Offset in bytes into indirectBuffer where the dispatch data begins. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let usageScope be an empty usage scope.
-
For each bindGroup in this.
[[bind_groups]], merge bindGroup.[[usedResources]]into this.[[usage scope]] -
If any of the following conditions are unsatisfied, invalidate this and return.
-
usageScope must satisfy usage scope validation.
-
Validate encoder bind groups(this, this.
[[pipeline]]) istrue. -
indirectBuffer is valid to use with this.
-
indirectOffset + sizeof(indirect dispatch parameters) ≤ indirectBuffer.
size. -
indirectOffset is a multiple of 4.
-
-
Let bindingState be a snapshot of this’s current state.
-
Enqueue a command on this which issues the subsequent steps on the Queue timeline.
Queue timeline steps:-
Let workgroupCountX be an unsigned 32-bit integer read from indirectBuffer at indirectOffset bytes.
-
Let workgroupCountY be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 4) bytes.
-
Let workgroupCountZ be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 8) bytes.
-
If workgroupCountX, workgroupCountY, or workgroupCountZ is greater than this.device.limits.
maxComputeWorkgroupsPerDimension, return. -
Execute a grid of workgroups with dimensions [workgroupCountX, workgroupCountY, workgroupCountZ] with bindingState.
[[pipeline]]using bindingState.[[bind_groups]].
-
16.1.3. Finalization
The compute pass encoder can be ended by calling end()
once the user
has finished recording commands for the pass. Once end()
has been
called the compute pass encoder can no longer be used.
end()-
Completes recording of the compute pass commands sequence.
Called on:GPUComputePassEncoderthis.Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Let parentEncoder be this.
[[command_encoder]]. -
If any of the following requirements are unmet, generate a validation error and return.
-
If any of the following requirements are unmet, invalidate parentEncoder and return.
-
this must be valid.
-
this.
[[debug_group_stack]]must be empty.
-
-
Extend parentEncoder.
[[commands]]with this.[[commands]]. -
If this.
[[endTimestampWrite]]is notnull:-
Extend parentEncoder.
[[commands]]with this.[[endTimestampWrite]].
-
-
17. Render Passes
17.1. GPURenderPassEncoder
[Exposed =(Window ,Worker ),SecureContext ]interface GPURenderPassEncoder {undefined setViewport (float x ,float y ,float width ,float height ,float minDepth ,float maxDepth );undefined setScissorRect (GPUIntegerCoordinate x ,GPUIntegerCoordinate y ,GPUIntegerCoordinate width ,GPUIntegerCoordinate height );undefined setBlendConstant (GPUColor color );undefined setStencilReference (GPUStencilValue reference );undefined beginOcclusionQuery (GPUSize32 queryIndex );undefined endOcclusionQuery ();undefined executeBundles (sequence <GPURenderBundle >bundles );undefined end (); };GPURenderPassEncoder includes GPUObjectBase ;GPURenderPassEncoder includes GPUCommandsMixin ;GPURenderPassEncoder includes GPUDebugCommandsMixin ;GPURenderPassEncoder includes GPUBindingCommandsMixin ;GPURenderPassEncoder includes GPURenderCommandsMixin ;
GPURenderPassEncoder
has the following device timeline properties:
[[command_encoder]], of typeGPUCommandEncoder, readonly-
The
GPUCommandEncoderthat created this render pass encoder. [[attachment_size]], readonly-
Set to the following extents:
-
width, height= the dimensions of the pass’s render attachments
-
[[occlusion_query_set]], of typeGPUQuerySet, readonly-
The
GPUQuerySetto store occlusion query results for the pass, which is initialized withGPURenderPassDescriptor.occlusionQuerySetat pass creation time. [[endTimestampWrite]], of type GPU command?, readonly, defaulting tonull-
GPU command, if any, writing a timestamp when the pass ends.
[[maxDrawCount]]of typeGPUSize64, readonly-
The maximum number of draws allowed in this pass.
[[occlusion_query_active]], of typeboolean-
Whether the pass’s
[[occlusion_query_set]]is being written.
When executing encoded render pass commands as part of a GPUCommandBuffer,
an internal
RenderState object is used
to track the current state required for rendering.
RenderState has the following queue timeline properties:
[[occlusionQueryIndex]], of typeGPUSize32-
The index into
[[occlusion_query_set]]at which to store the occlusion query results. [[viewport]]-
Current viewport rectangle and depth range. Initially set to the following values:
-
x, y=0.0, 0.0 -
width, height= the dimensions of the pass’s render targets -
minDepth, maxDepth=0.0, 1.0
-
[[scissorRect]]-
Current scissor rectangle. Initially set to the following values:
-
x, y=0, 0 -
width, height= the dimensions of the pass’s render targets
-
[[blendConstant]], of typeGPUColor-
Current blend constant value, initially
[0, 0, 0, 0]. [[stencilReference]], of typeGPUStencilValue-
Current stencil reference value, initially
0. [[colorAttachments]], of type sequence<GPURenderPassColorAttachment?>-
The color attachments and state for this render pass.
[[depthStencilAttachment]], of typeGPURenderPassDepthStencilAttachment?-
The depth/stencil attachment and state for this render pass.
Render passes also have framebuffer memory, which contains the texel data associated with each attachment that is written into by draw commands and read from for blending and depth/stencil testing.
Note: Depending on the GPU hardware, framebuffer memory may be the memory allocated by the attachment textures or may be a separate area of memory that the texture data is copied to and from, such as with tile-based architectures.
17.1.1. Render Pass Encoder Creation
dictionary {GPURenderPassTimestampWrites required GPUQuerySet querySet ;GPUSize32 beginningOfPassWriteIndex ;GPUSize32 endOfPassWriteIndex ; };
querySet, of type GPUQuerySet-
The
GPUQuerySet, of type"timestamp", that the query results will be written to. beginningOfPassWriteIndex, of type GPUSize32-
If defined, indicates the query index in
querySetinto which the timestamp at the beginning of the render pass will be written. endOfPassWriteIndex, of type GPUSize32-
If defined, indicates the query index in
querySetinto which the timestamp at the end of the render pass will be written.
Note: Timestamp query values are written in nanoseconds, but how the value is determined is implementation-defined and may not increase monotonically. See § 20.4 Timestamp Query for details.
dictionary :GPURenderPassDescriptor GPUObjectDescriptorBase {required sequence <GPURenderPassColorAttachment ?>colorAttachments ;GPURenderPassDepthStencilAttachment depthStencilAttachment ;GPUQuerySet occlusionQuerySet ;GPURenderPassTimestampWrites timestampWrites ;GPUSize64 maxDrawCount = 50000000; };
colorAttachments, of typesequence<GPURenderPassColorAttachment?>-
The set of
GPURenderPassColorAttachmentvalues in this sequence defines which color attachments will be output to when executing this render pass.Due to usage compatibility, no color attachment may alias another attachment or any resource used inside the render pass.
depthStencilAttachment, of type GPURenderPassDepthStencilAttachment-
The
GPURenderPassDepthStencilAttachmentvalue that defines the depth/stencil attachment that will be output to and tested against when executing this render pass.Due to usage compatibility, no writable depth/stencil attachment may alias another attachment or any resource used inside the render pass.
occlusionQuerySet, of type GPUQuerySet-
The
GPUQuerySetvalue defines where the occlusion query results will be stored for this pass. timestampWrites, of type GPURenderPassTimestampWrites-
Defines which timestamp values will be written for this pass, and where to write them to.
maxDrawCount, of type GPUSize64, defaulting to50000000-
The maximum number of draw calls that will be done in the render pass. Used by some implementations to size work injected before the render pass. Keeping the default value is a good default, unless it is known that more draw calls will be done.
Given a GPUDevice
device and GPURenderPassDescriptor
this, the following validation rules apply:
-
this.
colorAttachments.size must be ≤ device.[[limits]].maxColorAttachments. -
For each non-
nullcolorAttachment in this.colorAttachments:-
colorAttachment.
viewmust be valid to use with device. -
If colorAttachment.
resolveTargetis provided:-
colorAttachment.
resolveTargetmust be valid to use with device.
-
-
colorAttachment must meet the GPURenderPassColorAttachment Valid Usage rules.
-
-
If this.
depthStencilAttachmentis provided:-
this.
depthStencilAttachment.viewmust be valid to use with device. -
this.
depthStencilAttachmentmust meet the GPURenderPassDepthStencilAttachment Valid Usage rules.
-
-
There must exist at least one attachment, either:
-
A non-
nullvalue in this.colorAttachments, or -
A this.
depthStencilAttachment.
-
-
Validating GPURenderPassDescriptor’s color attachment bytes per sample(device, this.
colorAttachments) succeeds. -
All
views in non-nullmembers of this.colorAttachments, and this.depthStencilAttachment.viewif present, must have equalsampleCounts. -
For each
viewin non-nullmembers of this.colorAttachmentsand this.depthStencilAttachment.view, if present, the[[renderExtent]]must match. -
If this.
occlusionQuerySetis provided:-
this.
occlusionQuerySetmust be valid to use with device. -
this.
occlusionQuerySet.typemust beocclusion.
-
-
If this.
timestampWritesis provided:-
Validate timestampWrites(device, this.
timestampWrites) must return true.
-
Arguments:
-
GPUDevicedevice -
sequence<
GPURenderPassColorAttachment?> colorAttachments
Device timeline steps:
-
Let formats be an empty list<
GPUTextureFormat?> -
For each colorAttachment in colorAttachments:
-
If colorAttachment is
undefined, continue. -
Append colorAttachment.
view.[[descriptor]].formatto formats.
-
-
Calculating color attachment bytes per sample(formats) must be ≤ device.
[[limits]].maxColorAttachmentBytesPerSample.
17.1.1.1. Color Attachments
dictionary {GPURenderPassColorAttachment required (GPUTexture or GPUTextureView )view ;GPUIntegerCoordinate depthSlice ; (GPUTexture or GPUTextureView )resolveTarget ;GPUColor clearValue ;required GPULoadOp loadOp ;required GPUStoreOp storeOp ; };
view, of type(GPUTexture or GPUTextureView)-
Describes the texture subresource that will be output to for this color attachment. The subresource is determined by calling get as texture view(
view). depthSlice, of type GPUIntegerCoordinate-
Indicates the depth slice index of
"3d"viewthat will be output to for this color attachment. resolveTarget, of type(GPUTexture or GPUTextureView)-
Describes the texture subresource that will receive the resolved output for this color attachment if
viewis multisampled. The subresource is determined by calling get as texture view(resolveTarget). clearValue, of type GPUColor-
Indicates the value to clear
viewto prior to executing the render pass. If not provided, defaults to{r: 0, g: 0, b: 0, a: 0}. Ignored ifloadOpis not"clear".The components of
clearValueare all double values. They are converted to a texel value of texture format matching the render attachment. If conversion fails, a validation error is generated. loadOp, of type GPULoadOp-
Indicates the load operation to perform on
viewprior to executing the render pass.Note: It is recommended to prefer clearing; see
"clear"for details. storeOp, of type GPUStoreOp-
The store operation to perform on
viewafter executing the render pass.
Given a GPURenderPassColorAttachment
this:
-
Let renderViewDescriptor be this.
view.[[descriptor]]. -
Let renderTexture be this.
view.[[texture]]. -
All of the requirements in the following steps must be met.
-
renderViewDescriptor.
formatmust be a color renderable format. -
this.
viewmust be a renderable texture view. -
If renderViewDescriptor.
dimensionis"3d":-
this.
depthSlicemust be provided and must be < the depthOrArrayLayers of the logical miplevel-specific texture extent of the renderTexture subresource at mipmap level renderViewDescriptor.baseMipLevel.
Otherwise:
-
this.
depthSlicemust not be provided.
-
-
-
Converting the IDL value this.
clearValueto a texel value of texture format renderViewDescriptor.formatmust not throw aTypeError.Note: An error is not thrown if the value is out-of-range for the format but in-range for the corresponding WGSL primitive type (
f32,i32, oru32).
-
-
If this.
resolveTargetis provided:-
Let resolveViewDescriptor be this.
resolveTarget.[[descriptor]]. -
Let resolveTexture be this.
resolveTarget.[[texture]]. -
renderTexture.
sampleCountmust be > 1. -
resolveTexture.
sampleCountmust be 1. -
this.
resolveTargetmust be a non-3d renderable texture view. -
this.
resolveTarget.[[renderExtent]]and this.view.[[renderExtent]]must match. -
resolveViewDescriptor.
formatmust equal renderViewDescriptor.format. -
resolveViewDescriptor.
formatmust support resolve according to § 26.1.1 Plain color formats.
-
-
GPUTextureView
view is a renderable texture view
if the all of the requirements in the following device timeline steps are met:
-
Let descriptor be view.
[[descriptor]]. -
descriptor.
usagemust containRENDER_ATTACHMENT. -
descriptor.
dimensionmust be"2d"or"2d-array"or"3d". -
descriptor.
mipLevelCountmust be 1. -
descriptor.
arrayLayerCountmust be 1. -
descriptor.
aspectmust refer to all aspects of view.[[texture]].
Arguments:
-
sequence<
GPUTextureFormat?> formats
Returns: GPUSize32
-
Let total be 0.
-
For each non-null format in formats
-
Assert: format is a color renderable format.
-
Let renderTargetPixelByteCost be the render target pixel byte cost of format.
-
Let renderTargetComponentAlignment be the render target component alignment of format.
-
Round total up to the smallest multiple of renderTargetComponentAlignment greater than or equal to total.
-
Add renderTargetPixelByteCost to total.
-
-
Return total.
17.1.1.2. Depth/Stencil Attachments
dictionary {GPURenderPassDepthStencilAttachment required (GPUTexture or GPUTextureView )view ;float depthClearValue ;GPULoadOp depthLoadOp ;GPUStoreOp depthStoreOp ;boolean depthReadOnly =false ;GPUStencilValue stencilClearValue = 0;GPULoadOp stencilLoadOp ;GPUStoreOp stencilStoreOp ;boolean stencilReadOnly =false ; };
view, of type(GPUTexture or GPUTextureView)-
Describes the texture subresource that will be output to and read from for this depth/stencil attachment. The subresource is determined by calling get as texture view(
view). depthClearValue, of type float-
Indicates the value to clear
view’s depth component to prior to executing the render pass. Ignored ifdepthLoadOpis not"clear". Must be between 0.0 and 1.0, inclusive. depthLoadOp, of type GPULoadOp-
Indicates the load operation to perform on
view’s depth component prior to executing the render pass.Note: It is recommended to prefer clearing; see
"clear"for details. depthStoreOp, of type GPUStoreOp-
The store operation to perform on
view’s depth component after executing the render pass. depthReadOnly, of type boolean, defaulting tofalse-
Indicates that the depth component of
viewis read only. stencilClearValue, of type GPUStencilValue, defaulting to0-
Indicates the value to clear
view’s stencil component to prior to executing the render pass. Ignored ifstencilLoadOpis not"clear".The value will be converted to the type of the stencil aspect of view by taking the same number of LSBs as the number of bits in the stencil aspect of one texel of view.
stencilLoadOp, of type GPULoadOp-
Indicates the load operation to perform on
view’s stencil component prior to executing the render pass.Note: It is recommended to prefer clearing; see
"clear"for details. stencilStoreOp, of type GPUStoreOp-
The store operation to perform on
view’s stencil component after executing the render pass. stencilReadOnly, of type boolean, defaulting tofalse-
Indicates that the stencil component of
viewis read only.
Given a GPURenderPassDepthStencilAttachment
this, the following validation
rules apply:
-
this.
viewmust have a depth-or-stencil format. -
this.
viewmust be a renderable texture view. -
Let format be this.
view.[[descriptor]].format. -
If this.
depthLoadOpis"clear", this.depthClearValuemust be provided and must be between 0.0 and 1.0, inclusive. -
If format has a depth aspect and this.
depthReadOnlyisfalse:-
this.
depthLoadOpmust be provided. -
this.
depthStoreOpmust be provided.
Otherwise:
-
this.
depthLoadOpmust not be provided. -
this.
depthStoreOpmust not be provided.
-
-
If format has a stencil aspect and this.
stencilReadOnlyisfalse:-
this.
stencilLoadOpmust be provided. -
this.
stencilStoreOpmust be provided.
Otherwise:
-
this.
stencilLoadOpmust not be provided. -
this.
stencilStoreOpmust not be provided.
-
17.1.1.3. Load & Store Operations
enum {GPULoadOp "load" ,"clear" , };
"load"-
Loads the existing value for this attachment into the render pass.
"clear"-
Loads a clear value for this attachment into the render pass.
Note: On some GPU hardware (primarily mobile),
"clear"is significantly cheaper because it avoids loading data from main memory into tile-local memory. On other GPU hardware, there isn’t a significant difference. As a result, it is recommended to use"clear"rather than"load"in cases where the initial value doesn’t matter (e.g. the render target will be cleared using a skybox).
enum {GPUStoreOp "store" ,"discard" , };
"store"-
Stores the resulting value of the render pass for this attachment.
"discard"-
Discards the resulting value of the render pass for this attachment.
Note: Discarded attachments behave as if they are cleared to zero, but implementations are not required to perform a clear at the end of the render pass. Implementations which do not explicitly clear discarded attachments at the end of a pass must lazily clear them prior to the reading the attachment contents, which occurs via sampling, copies, attaching to a later render pass with
"load", displaying or reading back the canvas (get a copy of the image contents of a context), etc.
17.1.1.4. Render Pass Layout
GPURenderPassLayout
declares the layout of the render targets of a GPURenderBundle.
It is also used internally to describe
GPURenderPassEncoder
layouts and
GPURenderPipeline
layouts.
It determines compatibility between render passes, render bundles, and render pipelines.
dictionary :GPURenderPassLayout GPUObjectDescriptorBase {required sequence <GPUTextureFormat ?>colorFormats ;GPUTextureFormat depthStencilFormat ;GPUSize32 sampleCount = 1; };
colorFormats, of typesequence<GPUTextureFormat?>-
A list of the
GPUTextureFormats of the color attachments for this pass or bundle. depthStencilFormat, of type GPUTextureFormat-
The
GPUTextureFormatof the depth/stencil attachment for this pass or bundle. sampleCount, of type GPUSize32, defaulting to1-
Number of samples per pixel in the attachments for this pass or bundle.
GPURenderPassLayout
values are equal if:
-
Their
depthStencilFormatandsampleCountare equal, and -
Their
colorFormatsare equal ignoring any trailingnulls.
Arguments:
-
GPURenderPassDescriptordescriptor
Returns: GPURenderPassLayout
Device timeline steps:
-
Let layout be a new
GPURenderPassLayoutobject. -
For each colorAttachment in descriptor.
colorAttachments:-
If colorAttachment is not
null:-
Set layout.
sampleCountto colorAttachment.view.[[texture]].sampleCount. -
Append colorAttachment.
view.[[descriptor]].formatto layout.colorFormats.
-
-
Otherwise:
-
Append
nullto layout.colorFormats.
-
-
-
Let depthStencilAttachment be descriptor.
depthStencilAttachment. -
If depthStencilAttachment is not
null:-
Let view be depthStencilAttachment.
view. -
Set layout.
sampleCountto view.[[texture]].sampleCount. -
Set layout.
depthStencilFormatto view.[[descriptor]].format.
-
-
Return layout.
Arguments:
-
GPURenderPipelineDescriptordescriptor
Returns: GPURenderPassLayout
Device timeline steps:
-
Let layout be a new
GPURenderPassLayoutobject. -
Set layout.
sampleCountto descriptor.multisample.count. -
If descriptor.
depthStencilis provided:-
Set layout.
depthStencilFormatto descriptor.depthStencil.format.
-
-
If descriptor.
fragmentis provided:-
For each colorTarget in descriptor.
fragment.targets:-
Append colorTarget.
formatto layout.colorFormatsif colorTarget is notnull, or appendnullotherwise.
-
-
-
Return layout.
17.1.2. Finalization
The render pass encoder can be ended by calling end()
once the user
has finished recording commands for the pass. Once end()
has been
called the render pass encoder can no longer be used.
end()-
Completes recording of the render pass commands sequence.
Called on:GPURenderPassEncoderthis.Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Let parentEncoder be this.
[[command_encoder]]. -
If any of the following requirements are unmet, generate a validation error and return.
-
If any of the following requirements are unmet, invalidate parentEncoder and return.
-
this must be valid.
-
this.
[[usage scope]]must satisfy usage scope validation. -
this.
[[debug_group_stack]]must be empty. -
this.
[[occlusion_query_active]]must befalse. -
this.
[[drawCount]]must be ≤ this.[[maxDrawCount]].
-
-
Extend parentEncoder.
[[commands]]with this.[[commands]]. -
If this.
[[endTimestampWrite]]is notnull:-
Extend parentEncoder.
[[commands]]with this.[[endTimestampWrite]].
-
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
For each non-
nullcolorAttachment in renderState.[[colorAttachments]]:-
Let colorView be colorAttachment.
view. -
If colorView.
[[descriptor]].dimensionis:"3d"-
Let colorSubregion be colorAttachment.
depthSliceof colorView. - Otherwise
-
Let colorSubregion be colorView.
-
If colorAttachment.
resolveTargetis notnull:-
Resolve the multiple samples of every texel of colorSubregion to a single sample and copy to colorAttachment.
resolveTarget.
-
-
If colorAttachment.
loadOpis:"store"-
Ensure the contents of the framebuffer memory associated with colorSubregion are stored in colorSubregion.
"discard"-
Set every texel of colorSubregion to zero.
-
-
Let depthStencilAttachment be renderState.
[[depthStencilAttachment]]. -
If depthStencilAttachment is not
null:-
If depthStencilAttachment.
depthLoadOpis:- Not provided
-
Assert that depthStencilAttachment.
depthReadOnlyistrueand leave the depth subresource of depthStencilView unchanged. "store"-
Ensure the contents of the framebuffer memory associated with the depth subresource of depthStencilView are stored in depthStencilView.
"discard"-
Set every texel in the depth subresource of depthStencilView to zero.
-
If depthStencilAttachment.
stencilLoadOpis:- Not provided
-
Assert that depthStencilAttachment.
stencilReadOnlyistrueand leave the stencil subresource of depthStencilView unchanged. "store"-
Ensure the contents of the framebuffer memory associated with the stencil subresource of depthStencilView are stored in depthStencilView.
"discard"-
Set every texel in the stencil subresource depthStencilView to zero.
-
-
Let renderState be
null.
Note: Discarded attachments behave as if they are cleared to zero, but implementations are not required to perform a clear at the end of the render pass. See the note on
"discard"for additional details.Note: Read-only depth-stencil attachments can be thought of as implicitly using the
"store"operation, but since their content is unchanged during the render pass implementations don’t need to update the attachment. Validation that requires the store op to not be provided for read-only attachments is done in GPURenderPassDepthStencilAttachment Valid Usage. -
17.2. GPURenderCommandsMixin
GPURenderCommandsMixin
defines rendering commands common to GPURenderPassEncoder
and GPURenderBundleEncoder.
interface mixin GPURenderCommandsMixin {undefined setPipeline (GPURenderPipeline pipeline );undefined setIndexBuffer (GPUBuffer buffer ,GPUIndexFormat indexFormat ,optional GPUSize64 offset = 0,optional GPUSize64 size );undefined setVertexBuffer (GPUIndex32 slot ,GPUBuffer ?buffer ,optional GPUSize64 offset = 0,optional GPUSize64 size );undefined draw (GPUSize32 vertexCount ,optional GPUSize32 instanceCount = 1,optional GPUSize32 firstVertex = 0,optional GPUSize32 firstInstance = 0);undefined drawIndexed (GPUSize32 indexCount ,optional GPUSize32 instanceCount = 1,optional GPUSize32 firstIndex = 0,optional GPUSignedOffset32 baseVertex = 0,optional GPUSize32 firstInstance = 0);undefined drawIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset );undefined drawIndexedIndirect (GPUBuffer indirectBuffer ,GPUSize64 indirectOffset ); };
GPURenderCommandsMixin
assumes the presence of
GPUObjectBase,
GPUCommandsMixin,
and GPUBindingCommandsMixin
members on the same object.
It must only be included by interfaces which also include those mixins.
GPURenderCommandsMixin
has the following device timeline properties:
[[layout]], of typeGPURenderPassLayout, readonly-
The layout of the render pass.
[[depthReadOnly]], of typeboolean, readonly-
If
true, indicates that the depth component is not modified. [[stencilReadOnly]], of typeboolean, readonly-
If
true, indicates that the stencil component is not modified. [[usage scope]], of type usage scope, initially empty-
The usage scope for this render pass or bundle.
[[pipeline]], of typeGPURenderPipeline, initiallynull-
The current
GPURenderPipeline. [[index_buffer]], of typeGPUBuffer, initiallynull-
The current buffer to read index data from.
[[index_format]], of typeGPUIndexFormat-
The format of the index data in
[[index_buffer]]. [[index_buffer_offset]], of typeGPUSize64-
The offset in bytes of the section of
[[index_buffer]]currently set. [[index_buffer_size]], of typeGPUSize64-
The size in bytes of the section of
[[index_buffer]]currently set, initially0. [[vertex_buffers]], of type ordered map<slot,GPUBuffer>, initially empty-
The current
GPUBuffers to read vertex data from for each slot. [[vertex_buffer_sizes]], of type ordered map<slot,GPUSize64>, initially empty-
The size in bytes of the section of
GPUBuffercurrently set for each slot. [[drawCount]], of typeGPUSize64-
The number of draw commands recorded in this encoder.
GPURenderCommandsMixin
encoder which
issues the steps of a GPU Command
command with RenderState renderState, run the
following device
timeline steps:
-
Append command to encoder.
[[commands]]. -
When command is executed as part of a
GPUCommandBuffercommandBuffer:-
Issue the steps of command with commandBuffer.
[[renderState]]as renderState.
-
17.2.1. Drawing
setPipeline(pipeline)-
Sets the current
GPURenderPipeline.Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.setPipeline(pipeline) method. Parameter Type Nullable Optional Description pipelineGPURenderPipeline✘ ✘ The render pipeline to use for subsequent drawing commands. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let pipelineTargetsLayout be derive render targets layout from pipeline(pipeline.
[[descriptor]]). -
If any of the following conditions are unsatisfied, invalidate this and return.
-
pipeline is valid to use with this.
-
this.
[[layout]]equals pipelineTargetsLayout. -
If pipeline.
[[writesDepth]]: this.[[depthReadOnly]]must befalse. -
If pipeline.
[[writesStencil]]: this.[[stencilReadOnly]]must befalse.
-
-
Set this.
[[pipeline]]to be pipeline.
-
setIndexBuffer(buffer, indexFormat, offset, size)-
Sets the current index buffer.
Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.setIndexBuffer(buffer, indexFormat, offset, size) method. Parameter Type Nullable Optional Description bufferGPUBuffer✘ ✘ Buffer containing index data to use for subsequent drawing commands. indexFormatGPUIndexFormat✘ ✘ Format of the index data contained in buffer. offsetGPUSize64✘ ✔ Offset in bytes into buffer where the index data begins. Defaults to 0.sizeGPUSize64✘ ✔ Size in bytes of the index data in buffer. Defaults to the size of the buffer minus the offset. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If size is missing, set size to max(0, buffer.
size- offset). -
If any of the following conditions are unsatisfied, invalidate this and return.
-
buffer is valid to use with this.
-
offset is a multiple of indexFormat’s byte size.
-
offset + size ≤ buffer.
size.
-
-
Add buffer to
[[usage scope]]with usage input. -
Set this.
[[index_buffer]]to be buffer. -
Set this.
[[index_format]]to be indexFormat. -
Set this.
[[index_buffer_offset]]to be offset. -
Set this.
[[index_buffer_size]]to be size.
-
setVertexBuffer(slot, buffer, offset, size)-
Sets the current vertex buffer for the given slot.
Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.setVertexBuffer(slot, buffer, offset, size) method. Parameter Type Nullable Optional Description slotGPUIndex32✘ ✘ The vertex buffer slot to set the vertex buffer for. bufferGPUBuffer?✔ ✘ Buffer containing vertex data to use for subsequent drawing commands. offsetGPUSize64✘ ✔ Offset in bytes into buffer where the vertex data begins. Defaults to 0.sizeGPUSize64✘ ✔ Size in bytes of the vertex data in buffer. Defaults to the size of the buffer minus the offset. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let bufferSize be 0 if buffer is
null, or buffer.sizeif not. -
If size is missing, set size to max(0, bufferSize - offset).
-
If any of the following requirements are unmet, invalidate this and return.
-
slot must be < this.
[[device]].[[limits]].maxVertexBuffers. -
offset must be a multiple of 4.
-
offset + size must be ≤ bufferSize.
-
-
If buffer is
null:-
Remove this.
[[vertex_buffers]][slot]. -
Remove this.
[[vertex_buffer_sizes]][slot].
Otherwise:
-
If any of the following requirements are unmet, invalidate this and return.
-
buffer must be valid to use with this.
-
-
Add buffer to
[[usage scope]]with usage input. -
Set this.
[[vertex_buffers]][slot] to be buffer. -
Set this.
[[vertex_buffer_sizes]][slot] to be size.
-
-
draw(vertexCount, instanceCount, firstVertex, firstInstance)-
Draws primitives. See § 23.2 Rendering for the detailed specification.
Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.draw(vertexCount, instanceCount, firstVertex, firstInstance) method. Parameter Type Nullable Optional Description vertexCountGPUSize32✘ ✘ The number of vertices to draw. instanceCountGPUSize32✘ ✔ The number of instances to draw. firstVertexGPUSize32✘ ✔ Offset into the vertex buffers, in vertices, to begin drawing from. firstInstanceGPUSize32✘ ✔ First instance to draw. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
All of the requirements in the following steps must be met. If any are unmet, invalidate this and return.
-
It must be valid to draw with this.
-
Let buffers be this.
[[pipeline]].[[descriptor]].vertex.buffers. -
For each
GPUIndex32slot from0to buffers.size (non-inclusive):-
If buffers[slot] is
null, continue. -
Let bufferSize be this.
[[vertex_buffer_sizes]][slot]. -
Let stride be buffers[slot].
arrayStride. -
Let attributes be buffers[slot].
attributes -
Let lastStride be the maximum value of (attribute.
offset+ byteSize(attribute.format)) over each attribute in attributes, or 0 if attributes is empty. -
Let strideCount be computed based on buffers[slot].
stepMode:"vertex"-
firstVertex + vertexCount
"instance"-
firstInstance + instanceCount
-
If strideCount ≠
0:-
(strideCount −
1) × stride + lastStride must be ≤ bufferSize.
-
-
-
-
Increment this.
[[drawCount]]by 1. -
Let bindingState be a snapshot of this’s current state.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Draw instanceCount instances, starting with instance firstInstance, of primitives consisting of vertexCount vertices, starting with vertex firstVertex, with the states from bindingState and renderState.
-
drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance)-
Draws indexed primitives. See § 23.2 Rendering for the detailed specification.
Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance) method. Parameter Type Nullable Optional Description indexCountGPUSize32✘ ✘ The number of indices to draw. instanceCountGPUSize32✘ ✔ The number of instances to draw. firstIndexGPUSize32✘ ✔ Offset into the index buffer, in indices, begin drawing from. baseVertexGPUSignedOffset32✘ ✔ Added to each index value before indexing into the vertex buffers. firstInstanceGPUSize32✘ ✔ First instance to draw. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
It is valid to draw indexed with this.
-
firstIndex + indexCount ≤ this.
[[index_buffer_size]]÷ this.[[index_format]]’s byte size; -
Let buffers be this.
[[pipeline]].[[descriptor]].vertex.buffers. -
For each
GPUIndex32slot from0to buffers.size (non-inclusive):-
If buffers[slot] is
null, continue. -
Let bufferSize be this.
[[vertex_buffer_sizes]][slot]. -
Let stride be buffers[slot].
arrayStride. -
Let lastStride be max(attribute.
offset+ byteSize(attribute.format)) for each attribute in buffers[slot].attributes. -
Let strideCount be firstInstance + instanceCount.
-
If buffers[slot].
stepModeis"instance"and strideCount ≠0:-
Ensure (strideCount −
1) × stride + lastStride ≤ bufferSize.
-
-
-
-
Increment this.
[[drawCount]]by 1. -
Let bindingState be a snapshot of this’s current state.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Draw instanceCount instances, starting with instance firstInstance, of primitives consisting of indexCount indexed vertices, starting with index firstIndex from vertex baseVertex, with the states from bindingState and renderState.
Note: WebGPU applications should never use index data with indices out of bounds of any bound vertex buffer that has
GPUVertexStepMode"vertex". WebGPU implementations have different ways of handling this, and therefore a range of behaviors is allowed. Either the whole draw call is discarded, or the access to those attributes out of bounds is described by WGSL’s invalid memory reference. -
drawIndirect(indirectBuffer, indirectOffset)-
Draws primitives using parameters read from a
GPUBuffer. See § 23.2 Rendering for the detailed specification.The indirect draw parameters encoded in the buffer must be a tightly packed block of four 32-bit unsigned integer values (16 bytes total), given in the same order as the arguments for
draw(). For example:let drawIndirectParameters= new Uint32Array( 4 ); drawIndirectParameters[ 0 ] = vertexCount; drawIndirectParameters[ 1 ] = instanceCount; drawIndirectParameters[ 2 ] = firstVertex; drawIndirectParameters[ 3 ] = firstInstance; The value corresponding to
firstInstancemust be 0, unless the"indirect-first-instance"feature is enabled. If the"indirect-first-instance"feature is not enabled andfirstInstanceis not zero thedrawIndirect()call will be treated as a no-op.Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.drawIndirect(indirectBuffer, indirectOffset) method. Parameter Type Nullable Optional Description indirectBufferGPUBuffer✘ ✘ Buffer containing the indirect draw parameters. indirectOffsetGPUSize64✘ ✘ Offset in bytes into indirectBuffer where the drawing data begins. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
It is valid to draw with this.
-
indirectBuffer is valid to use with this.
-
indirectOffset + sizeof(indirect draw parameters) ≤ indirectBuffer.
size. -
indirectOffset is a multiple of 4.
-
-
Add indirectBuffer to
[[usage scope]]with usage input. -
Increment this.
[[drawCount]]by 1. -
Let bindingState be a snapshot of this’s current state.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Let vertexCount be an unsigned 32-bit integer read from indirectBuffer at indirectOffset bytes.
-
Let instanceCount be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 4) bytes.
-
Let firstVertex be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 8) bytes.
-
Let firstInstance be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 12) bytes.
-
Draw instanceCount instances, starting with instance firstInstance, of primitives consisting of vertexCount vertices, starting with vertex firstVertex, with the states from bindingState and renderState.
-
drawIndexedIndirect(indirectBuffer, indirectOffset)-
Draws indexed primitives using parameters read from a
GPUBuffer. See § 23.2 Rendering for the detailed specification.The indirect drawIndexed parameters encoded in the buffer must be a tightly packed block of five 32-bit values (20 bytes total), given in the same order as the arguments for
drawIndexed(). The value corresponding tobaseVertexis a signed 32-bit integer, and all others are unsigned 32-bit integers. For example:let drawIndexedIndirectParameters= new Uint32Array( 5 ); let drawIndexedIndirectParametersSigned= new Int32Array( drawIndexedIndirectParameters. buffer); drawIndexedIndirectParameters[ 0 ] = indexCount; drawIndexedIndirectParameters[ 1 ] = instanceCount; drawIndexedIndirectParameters[ 2 ] = firstIndex; // baseVertex is a signed value. drawIndexedIndirectParametersSigned[ 3 ] = baseVertex; drawIndexedIndirectParameters[ 4 ] = firstInstance; The value corresponding to
firstInstancemust be 0, unless the"indirect-first-instance"feature is enabled. If the"indirect-first-instance"feature is not enabled andfirstInstanceis not zero thedrawIndexedIndirect()call will be treated as a no-op.Called on:GPURenderCommandsMixinthis.Arguments:
Arguments for the GPURenderCommandsMixin.drawIndexedIndirect(indirectBuffer, indirectOffset) method. Parameter Type Nullable Optional Description indirectBufferGPUBuffer✘ ✘ Buffer containing the indirect drawIndexed parameters. indirectOffsetGPUSize64✘ ✘ Offset in bytes into indirectBuffer where the drawing data begins. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
It is valid to draw indexed with this.
-
indirectBuffer is valid to use with this.
-
indirectOffset + sizeof(indirect drawIndexed parameters) ≤ indirectBuffer.
size. -
indirectOffset is a multiple of 4.
-
-
Add indirectBuffer to
[[usage scope]]with usage input. -
Increment this.
[[drawCount]]by 1. -
Let bindingState be a snapshot of this’s current state.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Let indexCount be an unsigned 32-bit integer read from indirectBuffer at indirectOffset bytes.
-
Let instanceCount be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 4) bytes.
-
Let firstIndex be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 8) bytes.
-
Let baseVertex be a signed 32-bit integer read from indirectBuffer at (indirectOffset + 12) bytes.
-
Let firstInstance be an unsigned 32-bit integer read from indirectBuffer at (indirectOffset + 16) bytes.
-
Draw instanceCount instances, starting with instance firstInstance, of primitives consisting of indexCount indexed vertices, starting with index firstIndex from vertex baseVertex, with the states from bindingState and renderState.
-
GPURenderCommandsMixin
encoder,
run the following device
timeline steps:
-
If any of the following conditions are unsatisfied, return
false:-
Validate encoder bind groups(encoder, encoder.
[[pipeline]]) must betrue. -
Let pipelineDescriptor be encoder.
[[pipeline]].[[descriptor]]. -
For each
GPUIndex32slot0to pipelineDescriptor.vertex.buffers.size:-
If pipelineDescriptor.
vertex.buffers[slot] is notnull, encoder.[[vertex_buffers]]must contain slot.
-
-
Validate
maxBindGroupsPlusVertexBuffers:-
Let bindGroupSpaceUsed be (the maximum key in encoder.
[[bind_groups]]) + 1. -
Let vertexBufferSpaceUsed be (the maximum key in encoder.
[[vertex_buffers]]) + 1. -
bindGroupSpaceUsed + vertexBufferSpaceUsed must be ≤ encoder.
[[device]].[[limits]].maxBindGroupsPlusVertexBuffers.
-
-
-
Otherwise return
true.
GPURenderCommandsMixin
encoder,
run the following device
timeline steps:
-
If any of the following conditions are unsatisfied, return
false:-
It must be valid to draw with encoder.
-
encoder.
[[index_buffer]]must not benull. -
Let topology be encoder.
[[pipeline]].[[descriptor]].primitive.topology. -
If topology is
"line-strip"or"triangle-strip":-
encoder.
[[index_format]]must equal encoder.[[pipeline]].[[descriptor]].primitive.stripIndexFormat.
-
-
-
Otherwise return
true.
17.2.2. Rasterization state
The GPURenderPassEncoder
has several methods which affect how draw commands are rasterized to
attachments used by this encoder.
setViewport(x, y, width, height, minDepth, maxDepth)-
Sets the viewport used during the rasterization stage to linearly map from normalized device coordinates to viewport coordinates.
Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setViewport(x, y, width, height, minDepth, maxDepth) method. Parameter Type Nullable Optional Description xfloat✘ ✘ Minimum X value of the viewport in pixels. yfloat✘ ✘ Minimum Y value of the viewport in pixels. widthfloat✘ ✘ Width of the viewport in pixels. heightfloat✘ ✘ Height of the viewport in pixels. minDepthfloat✘ ✘ Minimum depth value of the viewport. maxDepthfloat✘ ✘ Maximum depth value of the viewport. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Let maxViewportRange be this.
limits.maxTextureDimension2D×2. -
If any of the following conditions are unsatisfied, invalidate this and return.
-
x ≥ -maxViewportRange
-
y ≥ -maxViewportRange
-
0≤ width ≤ this.limits.maxTextureDimension2D -
0≤ height ≤ this.limits.maxTextureDimension2D -
x + width ≤ maxViewportRange −
1 -
y + height ≤ maxViewportRange −
1 -
0.0≤ minDepth ≤1.0 -
0.0≤ maxDepth ≤1.0 -
minDepth ≤ maxDepth
-
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Round x, y, width, and height to some uniform precision, no less precise than integer rounding.
-
Set renderState.
[[viewport]]to the extents x, y, width, height, minDepth, and maxDepth.
-
setScissorRect(x, y, width, height)-
Sets the scissor rectangle used during the rasterization stage. After transformation into viewport coordinates any fragments which fall outside the scissor rectangle will be discarded.
Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setScissorRect(x, y, width, height) method. Parameter Type Nullable Optional Description xGPUIntegerCoordinate✘ ✘ Minimum X value of the scissor rectangle in pixels. yGPUIntegerCoordinate✘ ✘ Minimum Y value of the scissor rectangle in pixels. widthGPUIntegerCoordinate✘ ✘ Width of the scissor rectangle in pixels. heightGPUIntegerCoordinate✘ ✘ Height of the scissor rectangle in pixels. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
x+width ≤ this.
[[attachment_size]].width. -
y+height ≤ this.
[[attachment_size]].height.
-
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Set renderState.
[[scissorRect]]to the extents x, y, width, and height.
-
setBlendConstant(color)-
Sets the constant blend color and alpha values used with
"constant"and"one-minus-constant"GPUBlendFactors.Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setBlendConstant(color) method. Parameter Type Nullable Optional Description colorGPUColor✘ ✘ The color to use when blending. Returns:
undefinedContent timeline steps:
-
? validate GPUColor shape(color).
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Set renderState.
[[blendConstant]]to color.
-
setStencilReference(reference)-
Sets the
[[stencilReference]]value used during stencil tests with the"replace"GPUStencilOperation.Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.setStencilReference(reference) method. Parameter Type Nullable Optional Description referenceGPUStencilValue✘ ✘ The new stencil reference value. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Set renderState.
[[stencilReference]]to reference.
-
17.2.3. Queries
beginOcclusionQuery(queryIndex)-
Called on:
GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.beginOcclusionQuery(queryIndex) method. Parameter Type Nullable Optional Description queryIndexGPUSize32✘ ✘ The index of the query in the query set. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
this.
[[occlusion_query_set]]is notnull. -
queryIndex < this.
[[occlusion_query_set]].count. -
The query at same queryIndex must not have been previously written to in this pass.
-
this.
[[occlusion_query_active]]isfalse.
-
-
Set this.
[[occlusion_query_active]]totrue. -
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Set renderState.
[[occlusionQueryIndex]]to queryIndex.
-
endOcclusionQuery()-
Called on:
GPURenderPassEncoderthis.Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
this.
[[occlusion_query_active]]istrue.
-
-
Set this.
[[occlusion_query_active]]tofalse. -
Enqueue a render command on this which issues the subsequent steps on the Queue timeline with renderState when executed.
Queue timeline steps:-
Let passingFragments be non-zero if any fragment samples passed all per-fragment tests since the corresponding
beginOcclusionQuery()command was executed, and zero otherwise.Note: If no draw calls occurred, passingFragments is zero.
-
Write passingFragments into this.
[[occlusion_query_set]]at index renderState.[[occlusionQueryIndex]].
-
17.2.4. Bundles
executeBundles(bundles)-
Executes the commands previously recorded into the given
GPURenderBundles as part of this render pass.When a
GPURenderBundleis executed, it does not inherit the render pass’s pipeline, bind groups, or vertex and index buffers. After aGPURenderBundlehas executed, the render pass’s pipeline, bind group, and vertex/index buffer state is cleared (to the initial, empty values).Note: The state is cleared, not restored to the previous state. This occurs even if zero
GPURenderBundlesare executed.Called on:GPURenderPassEncoderthis.Arguments:
Arguments for the GPURenderPassEncoder.executeBundles(bundles) method. Parameter Type Nullable Optional Description bundlessequence<GPURenderBundle>✘ ✘ List of render bundles to execute. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
[[device]].
Device timeline steps:-
Validate the encoder state of this. If it returns false, return.
-
If any of the following conditions are unsatisfied, invalidate this and return.
-
For each bundle in bundles:
-
bundle must be valid to use with this.
-
this.
[[layout]]must equal bundle.[[layout]]. -
If this.
[[depthReadOnly]]is true, bundle.[[depthReadOnly]]must be true. -
If this.
[[stencilReadOnly]]is true, bundle.[[stencilReadOnly]]must be true.
-
-
-
For each bundle in bundles:
-
Increment this.
[[drawCount]]by bundle.[[drawCount]]. -
Merge bundle.
[[usage scope]]into this.[[usage scope]]. -
Enqueue a render command on this which issues the following steps on the Queue timeline with renderState when executed:
Queue timeline steps:-
Execute each command in bundle.
[[command_list]]with renderState.Note: renderState cannot be changed by executing render bundles. Binding state was already captured at bundle encoding time, and so isn’t used when executing bundles.
-
-
-
Reset the render pass binding state of this.
-
GPURenderPassEncoder
encoder run
the following device
timeline steps:
-
Clear encoder.
[[bind_groups]]. -
Set encoder.
[[pipeline]]tonull. -
Set encoder.
[[index_buffer]]tonull. -
Clear encoder.
[[vertex_buffers]].
18. Bundles
A bundle is a partial, limited pass that is encoded once and can then be executed multiple times as part of future pass encoders without expiring after use like typical command buffers. This can reduce the overhead of encoding and submission of commands which are issued repeatedly without changing.
18.1. GPURenderBundle
[Exposed =(Window ,Worker ),SecureContext ]interface GPURenderBundle { };GPURenderBundle includes GPUObjectBase ;
[[command_list]], of type list<GPU command>-
A list of GPU commands to be submitted to the
GPURenderPassEncoderwhen theGPURenderBundleis executed. [[usage scope]], of type usage scope, initially empty-
The usage scope for this render bundle, stored for later merging into the
GPURenderPassEncoder’s[[usage scope]]inexecuteBundles(). [[layout]], of typeGPURenderPassLayout-
The layout of the render bundle.
[[depthReadOnly]], of typeboolean-
If
true, indicates that the depth component is not modified by executing this render bundle. [[stencilReadOnly]], of typeboolean-
If
true, indicates that the stencil component is not modified by executing this render bundle. [[drawCount]], of typeGPUSize64-
The number of draw commands in this
GPURenderBundle.
18.1.1. Render Bundle Creation
dictionary :GPURenderBundleDescriptor GPUObjectDescriptorBase { };
[Exposed =(Window ,Worker ),SecureContext ]interface {GPURenderBundleEncoder GPURenderBundle finish (optional GPURenderBundleDescriptor descriptor = {}); };GPURenderBundleEncoder includes GPUObjectBase ;GPURenderBundleEncoder includes GPUCommandsMixin ;GPURenderBundleEncoder includes GPUDebugCommandsMixin ;GPURenderBundleEncoder includes GPUBindingCommandsMixin ;GPURenderBundleEncoder includes GPURenderCommandsMixin ;
createRenderBundleEncoder(descriptor)-
Creates a
GPURenderBundleEncoder.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createRenderBundleEncoder(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderBundleEncoderDescriptor✘ ✘ Description of the GPURenderBundleEncoderto create.Returns:
GPURenderBundleEncoderContent timeline steps:
-
? Validate texture format required features of each non-
nullelement of descriptor.colorFormatswith this.[[device]]. -
If descriptor.
depthStencilFormatis provided:-
? Validate texture format required features of descriptor.
depthStencilFormatwith this.[[device]].
-
-
Let e be ! create a new WebGPU object(this,
GPURenderBundleEncoder, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return e.
Device timeline initialization steps:-
If any of the following conditions are unsatisfied generate a validation error, invalidate e and return.
-
this must not be lost.
-
descriptor.
colorFormats.size must be ≤ this.[[limits]].maxColorAttachments. -
For each non-
nullcolorFormat in descriptor.colorFormats:-
colorFormat must be a color renderable format.
-
-
Calculating color attachment bytes per sample(descriptor.
colorFormats) must be ≤ this.[[limits]].maxColorAttachmentBytesPerSample. -
If descriptor.
depthStencilFormatis provided:-
descriptor.
depthStencilFormatmust be a depth-or-stencil format.
-
-
There must exist at least one attachment, either:
-
A non-
nullvalue in descriptor.colorFormats, or -
A descriptor.
depthStencilFormat.
-
-
-
Set e.
[[layout]]to a copy of descriptor’s includedGPURenderPassLayoutinterface. -
Set e.
[[depthReadOnly]]to descriptor.depthReadOnly. -
Set e.
[[stencilReadOnly]]to descriptor.stencilReadOnly. -
Set e.
[[drawCount]]to 0.
-
18.1.2. Encoding
dictionary :GPURenderBundleEncoderDescriptor GPURenderPassLayout {boolean depthReadOnly =false ;boolean stencilReadOnly =false ; };
depthReadOnly, of type boolean, defaulting tofalse-
If
true, indicates that the render bundle does not modify the depth component of theGPURenderPassDepthStencilAttachmentof any render pass the render bundle is executed in. stencilReadOnly, of type boolean, defaulting tofalse-
If
true, indicates that the render bundle does not modify the stencil component of theGPURenderPassDepthStencilAttachmentof any render pass the render bundle is executed in.
18.1.3. Finalization
finish(descriptor)-
Completes recording of the render bundle commands sequence.
Called on:GPURenderBundleEncoderthis.Arguments:
Arguments for the GPURenderBundleEncoder.finish(descriptor) method. Parameter Type Nullable Optional Description descriptorGPURenderBundleDescriptor✘ ✔ Returns:
GPURenderBundleContent timeline steps:
-
Let renderBundle be a new
GPURenderBundle. -
Issue the finish steps on the Device timeline of this.
[[device]]. -
Return renderBundle.
Device timeline finish steps:-
Let validationSucceeded be
trueif all of the following requirements are met, andfalseotherwise.-
this must be valid.
-
this.
[[usage scope]]must satisfy usage scope validation. -
this.
[[debug_group_stack]]must be empty.
-
-
If validationSucceeded is
false, then:-
Return an invalidated
GPURenderBundle.
-
Set renderBundle.
[[command_list]]to this.[[commands]]. -
Set renderBundle.
[[usage scope]]to this.[[usage scope]]. -
Set renderBundle.
[[drawCount]]to this.[[drawCount]].
-
19. Queues
19.1. GPUQueueDescriptor
GPUQueueDescriptor
describes a queue request.
dictionary GPUQueueDescriptor :GPUObjectDescriptorBase { };
19.2. GPUQueue
[Exposed =(Window ,Worker ),SecureContext ]interface GPUQueue {undefined submit (sequence <GPUCommandBuffer >commandBuffers );Promise <undefined >onSubmittedWorkDone ();undefined writeBuffer (GPUBuffer buffer ,GPUSize64 bufferOffset ,AllowSharedBufferSource data ,optional GPUSize64 dataOffset = 0,optional GPUSize64 size );undefined writeTexture (GPUTexelCopyTextureInfo destination ,AllowSharedBufferSource data ,GPUTexelCopyBufferLayout dataLayout ,GPUExtent3D size );undefined copyExternalImageToTexture (GPUCopyExternalImageSourceInfo source ,GPUCopyExternalImageDestInfo destination ,GPUExtent3D copySize ); };GPUQueue includes GPUObjectBase ;
GPUQueue has
the following methods:
writeBuffer(buffer, bufferOffset, data, dataOffset, size)-
Issues a write operation of the provided data into a
GPUBuffer.Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.writeBuffer(buffer, bufferOffset, data, dataOffset, size) method. Parameter Type Nullable Optional Description bufferGPUBuffer✘ ✘ The buffer to write to. bufferOffsetGPUSize64✘ ✘ Offset in bytes into buffer to begin writing at. dataAllowSharedBufferSource✘ ✘ Data to write into buffer. dataOffsetGPUSize64✘ ✔ Offset in into data to begin writing from. Given in elements if data is a TypedArrayand bytes otherwise.sizeGPUSize64✘ ✔ Size of content to write from data to buffer. Given in elements if data is a TypedArrayand bytes otherwise.Returns:
undefinedContent timeline steps:
-
If data is an
ArrayBufferorDataView, let the element type be "byte". Otherwise, data is a TypedArray; let the element type be the type of the TypedArray. -
Let dataSize be the size of data, in elements.
-
If size is missing, let contentsSize be dataSize − dataOffset. Otherwise, let contentsSize be size.
-
If any of the following conditions are unsatisfied, throw an
OperationErrorand return.-
contentsSize ≥ 0.
-
dataOffset + contentsSize ≤ dataSize.
-
contentsSize, converted to bytes, is a multiple of 4 bytes.
-
-
Let dataContents be a copy of the bytes held by the buffer source data.
-
Let contents be the contentsSize elements of dataContents starting at an offset of dataOffset elements.
-
Issue the subsequent steps on the Device timeline of this.
Device timeline steps:-
If any of the following conditions are unsatisfied, generate a validation error and return.
-
buffer is valid to use with this.
-
buffer.
[[internal state]]is "available". -
bufferOffset, converted to bytes, is a multiple of 4 bytes.
-
bufferOffset + contentsSize, converted to bytes, ≤ buffer.
sizebytes.
-
-
Issue the subsequent steps on the Queue timeline of this.
Queue timeline steps:-
Write contents into buffer starting at bufferOffset.
-
writeTexture(destination, data, dataLayout, size)-
Issues a write operation of the provided data into a
GPUTexture.Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.writeTexture(destination, data, dataLayout, size) method. Parameter Type Nullable Optional Description destinationGPUTexelCopyTextureInfo✘ ✘ The texture subresource and origin to write to. dataAllowSharedBufferSource✘ ✘ Data to write into destination. dataLayoutGPUTexelCopyBufferLayout✘ ✘ Layout of the content in data. sizeGPUExtent3D✘ ✘ Extents of the content to write from data to destination. Returns:
undefinedContent timeline steps:
-
? validate GPUOrigin3D shape(destination.
origin). -
? validate GPUExtent3D shape(size).
-
Let dataBytes be a copy of the bytes held by the buffer source data.
Note: This is described as copying all of data to the device timeline, but in practice data could be much larger than necessary. Implementations should optimize by copying only the necessary bytes.
-
Issue the subsequent steps on the Device timeline of this.
Device timeline steps:-
Let aligned be
false. -
Let dataLength be dataBytes.length.
-
If any of the following conditions are unsatisfied, generate a validation error and return.
-
destination.
texture.[[destroyed]]isfalse. -
validating texture buffer copy(destination, dataLayout, dataLength, size,
COPY_DST, aligned) returnstrue.
Note: unlike
GPUCommandEncoder.copyBufferToTexture(), there is no alignment requirement on either dataLayout.bytesPerRowor dataLayout.offset. -
-
Issue the subsequent steps on the Queue timeline of this.
Queue timeline steps:-
Let blockWidth be the texel block width of destination.
texture. -
Let blockHeight be the texel block height of destination.
texture. -
Let dstOrigin be destination.
origin; -
Let dstBlockOriginX be (dstOrigin.x ÷ blockWidth).
-
Let dstBlockOriginY be (dstOrigin.y ÷ blockHeight).
-
Let blockColumns be (copySize.width ÷ blockWidth).
-
Let blockRows be (copySize.height ÷ blockHeight).
-
Assert that dstBlockOriginX, dstBlockOriginY, blockColumns, and blockRows are integers.
-
For each z in the range [0, copySize.depthOrArrayLayers − 1]:
-
Let dstSubregion be texture copy sub-region (z + dstOrigin.z) of destination.
-
For each y in the range [0, blockRows − 1]:
-
For each x in the range [0, blockColumns − 1]:
-
Let blockOffset be the texel block byte offset of dataLayout for (x, y, z) of destination.
texture. -
Set texel block (dstBlockOriginX + x, dstBlockOriginY + y) of dstSubregion to be an equivalent texel representation to the texel block described by dataBytes at offset blockOffset.
-
-
-
-
copyExternalImageToTexture(source, destination, copySize)-
Issues a copy operation of the contents of a platform image/canvas into the destination texture.
This operation performs color encoding into the destination encoding according to the parameters of
GPUCopyExternalImageDestInfo.Copying into a
-srgbtexture results in the same texture bytes, not the same decoded values, as copying into the corresponding non--srgbformat. Thus, after a copy operation, sampling the destination texture has different results depending on whether its format is-srgb, all else unchanged.NOTE:When copying from a"webgl"/"webgl2"context canvas, the WebGL Drawing Buffer may be not exist during certain points in the frame presentation cycle (after the image has been moved to the compositor for display). To avoid this, either:-
Issue
copyExternalImageToTexture()in the same task with WebGL rendering operation, to ensure the copy occurs before the WebGL canvas is presented. -
If not possible, set the
preserveDrawingBufferoption inWebGLContextAttributestotrue, so that the drawing buffer will still contain a copy of the frame contents after they’ve been presented. Note, this extra copy may have a performance cost.
Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.copyExternalImageToTexture(source, destination, copySize) method. Parameter Type Nullable Optional Description sourceGPUCopyExternalImageSourceInfo✘ ✘ source image and origin to copy to destination. destinationGPUCopyExternalImageDestInfo✘ ✘ The texture subresource and origin to write to, and its encoding metadata. copySizeGPUExtent3D✘ ✘ Extents of the content to write from source to destination. Returns:
undefinedContent timeline steps:
-
? validate GPUOrigin2D shape(source.
origin). -
? validate GPUOrigin3D shape(destination.
origin). -
? validate GPUExtent3D shape(copySize).
-
Let sourceImage be source.
source -
If sourceImage is not origin-clean, throw a
SecurityErrorand return. -
If any of the following requirements are unmet, throw an
OperationErrorand return.-
source.origin.x + copySize.width must be ≤ the width of sourceImage.
-
source.origin.y + copySize.height must be ≤ the height of sourceImage.
-
copySize.depthOrArrayLayers must be ≤ 1.
-
-
Let usability be ? check the usability of the image argument(source).
-
Issue the subsequent steps on the Device timeline of this.
Device timeline steps:-
Let texture be destination.
texture. -
If any of the following requirements are unmet, generate a validation error and return.
-
usability must be
good. -
texture.
[[destroyed]]must befalse. -
texture must be valid to use with this.
-
validating GPUTexelCopyTextureInfo(destination, copySize) must return
true. -
texture.
usagemust include bothRENDER_ATTACHMENTandCOPY_DST. -
texture.
sampleCountmust be 1. -
texture.
formatmust be one of the following formats (which all supportRENDER_ATTACHMENTusage):
-
-
If copySize.depthOrArrayLayers is > 0, issue the subsequent steps on the Queue timeline of this.
Queue timeline steps:-
Assert that the texel block width of destination.
textureis 1, the texel block height of destination.textureis 1, and that copySize.depthOrArrayLayers is 1. -
Let srcOrigin be source.
origin. -
Let dstOrigin be destination.
origin. -
Let dstSubregion be texture copy sub-region (dstOrigin.z) of destination.
-
For each y in the range [0, copySize.height − 1]:
-
Let srcY be y if source.
flipYisfalseand (copySize.height − 1 − y) otherwise. -
For each x in the range [0, copySize.width − 1]:
-
Set texel block (dstOrigin.x + x, dstOrigin.y + y) of dstSubregion to be an equivalent texel representation of the pixel at (srcOrigin.x + x, srcOrigin.y + srcY) of source.
sourceafter applying any color encoding required by destination.colorSpaceand destination.premultipliedAlpha.
-
-
-
submit(commandBuffers)-
Schedules the execution of the command buffers by the GPU on this queue.
Submitted command buffers cannot be used again.
Called on:GPUQueuethis.Arguments:
Arguments for the GPUQueue.submit(commandBuffers) method. Parameter Type Nullable Optional Description commandBufferssequence<GPUCommandBuffer>✘ ✘ Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this:
Device timeline steps:-
If any of the following requirements are unmet, generate a validation error, invalidate each
GPUCommandBufferin commandBuffers and return.-
Every
GPUCommandBufferin commandBuffers must be valid to use with this. -
Every
GPUCommandBufferin commandBuffers must be unique. -
For each of the following types of resources used by any command in any element of commandBuffers:
GPUBufferb-
b.
[[internal state]]must be "available". GPUTexturet-
t.
[[destroyed]]must befalse. GPUExternalTextureet-
et.
[[expired]]must befalse. GPUQuerySetqs-
qs.
[[destroyed]]must befalse.
Note: For occlusion queries, the
occlusionQuerySetinbeginRenderPass()is not "used" unless it is also used bybeginOcclusionQuery().
-
-
For each commandBuffer in commandBuffers:
-
Invalidate commandBuffer.
-
-
Issue the subsequent steps on the Queue timeline of this:
Queue timeline steps:-
For each commandBuffer in commandBuffers:
-
Execute each command in commandBuffer.
[[command_list]].
-
-
onSubmittedWorkDone()-
Returns a
Promisethat resolves once this queue finishes processing all the work submitted up to this moment.Resolution of this
Promiseimplies the completion ofmapAsync()calls made prior to that call, onGPUBuffers last used exclusively on that queue.Called on:GPUQueuethis.Content timeline steps:
-
Let contentTimeline be the current Content timeline.
-
Let promise be a new promise.
-
Issue the synchronization steps on the Device timeline of this.
-
Return promise.
Device timeline synchronization steps:-
Let event occur upon the completion of all currently-enqueued operations.
-
Listen for timeline event event on this.
[[device]], handled by the subsequent steps on contentTimeline.
Content timeline steps:-
Resolve promise.
-
20. Queries
20.1. GPUQuerySet
[Exposed =(Window ,Worker ),SecureContext ]interface GPUQuerySet {undefined destroy ();readonly attribute GPUQueryType type ;readonly attribute GPUSize32Out count ; };GPUQuerySet includes GPUObjectBase ;
GPUQuerySet
has the following immutable properties:
type, of type GPUQueryType, readonly-
The type of the queries managed by this
GPUQuerySet. count, of type GPUSize32Out, readonly-
The number of queries managed by this
GPUQuerySet.
GPUQuerySet
has the following device timeline properties:
[[destroyed]], of typeboolean, initiallyfalse-
If the query set is destroyed, it can no longer be used in any operation, and its underlying memory can be freed.
20.1.1. QuerySet Creation
A GPUQuerySetDescriptor
specifies the options to use in creating a GPUQuerySet.
dictionary :GPUQuerySetDescriptor GPUObjectDescriptorBase {required GPUQueryType type ;required GPUSize32 count ; };
type, of type GPUQueryType-
The type of queries managed by
GPUQuerySet. count, of type GPUSize32-
The number of queries managed by
GPUQuerySet.
createQuerySet(descriptor)-
Creates a
GPUQuerySet.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.createQuerySet(descriptor) method. Parameter Type Nullable Optional Description descriptorGPUQuerySetDescriptor✘ ✘ Description of the GPUQuerySetto create.Returns:
GPUQuerySetContent timeline steps:
-
If descriptor.
typeis"timestamp", but"timestamp-query"is not enabled for this:-
Throw a
TypeError.
-
-
Let q be ! create a new WebGPU object(this,
GPUQuerySet, descriptor). -
Issue the initialization steps on the Device timeline of this.
-
Return q.
Device timeline initialization steps:-
If any of the following requirements are unmet, generate a validation error, invalidate q and return.
-
Create a device allocation for q where each entry in the query set is zero.
If the allocation fails without side-effects, generate an out-of-memory error, invalidate q, and return.
-
GPUQuerySet
which holds 32 occlusion query results.
const querySet= gpuDevice. createQuerySet({ type: 'occlusion' , count: 32 });
20.1.2. Query Set Destruction
An application that no longer requires a GPUQuerySet
can choose to lose access to it before
garbage collection by calling destroy().
GPUQuerySet
has the following methods:
destroy()-
Destroys the
GPUQuerySet.Called on:GPUQuerySetthis.Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the device timeline.
Device timeline steps:-
Set this.
[[destroyed]]totrue.
-
20.2. QueryType
enum {GPUQueryType ,"occlusion" , };"timestamp"
20.3. Occlusion Query
Occlusion query is only available on render passes, to query the number of fragment samples that pass all the per-fragment tests for a set of drawing commands, including scissor, sample mask, alpha to coverage, stencil, and depth tests. Any non-zero result value for the query indicates that at least one sample passed the tests and reached the output merging stage of the render pipeline, 0 indicates that no samples passed the tests.
When beginning a render pass, GPURenderPassDescriptor.occlusionQuerySet
must be set to be able to use occlusion queries during the pass. An occlusion query is begun
and ended by calling beginOcclusionQuery()
and
endOcclusionQuery()
in pairs that cannot be nested, and resolved into a
GPUBuffer
as a 64-bit unsigned integer by GPUCommandEncoder.resolveQuerySet().
20.4. Timestamp Query
Timestamp queries allow applications to write timestamps to a GPUQuerySet,
using:
and then resolve timestamp values (in nanoseconds as a 64-bit unsigned
integer) into
a GPUBuffer,
using GPUCommandEncoder.resolveQuerySet().
Timestamp values are implementation-defined and may not increase monotonically. The physical device may reset the timestamp counter occasionally, which can result in unexpected values such as negative deltas between timestamps that logically should be monotonically increasing. These instances should be rare and can safely be ignored. Applications should not be written in such a way that unexpected timestamps cause an application failure.
Timestamp queries are implemented using high-resolution timers (see § 2.1.7.2 Device/queue-timeline timing). To mitigate security and privacy concerns, their precision must be reduced:
-
Let fineTimestamp be the current timestamp value of the current queue timeline, in nanoseconds, relative to an implementation-defined point in the past.
-
Return the result of calling coarsen time on fineTimestamp with
crossOriginIsolatedCapabilityset tofalse.
Note: Since cross-origin isolation may not apply to
the device timeline
or
queue timeline,
crossOriginIsolatedCapability is never set to true.
Arguments:
-
GPUDevicedevice -
(timestampWritesGPUComputePassTimestampWritesorGPURenderPassTimestampWrites)
Device timeline steps:
-
Return
trueif the following requirements are met, andfalseif not:-
"timestamp-query"must be enabled for device. -
timestampWrites.
querySetmust be valid to use with device. -
timestampWrites.
querySet.typemust be"timestamp". -
Of the write index members in timestampWrites (
beginningOfPassWriteIndex,endOfPassWriteIndex):
-
21. Canvas Rendering
21.1. HTMLCanvasElement.getContext()
A GPUCanvasContext
object is created
via the getContext()
method of an HTMLCanvasElement
instance by passing the string literal 'webgpu' as its contextType argument.
GPUCanvasContext
from an offscreen HTMLCanvasElement:
const canvas= document. createElement( 'canvas' ); const context= canvas. getContext( 'webgpu' );
Unlike WebGL or 2D context creation, the second argument of
HTMLCanvasElement.getContext()
or
OffscreenCanvas.getContext(),
the context creation attribute dictionary options, is ignored.
Instead, use GPUCanvasContext.configure(),
which allows changing the canvas configuration without replacing the canvas.
HTMLCanvasElement
or OffscreenCanvas)
canvas, run the following
content timeline
steps:
-
Let context be a new
GPUCanvasContext. -
Set context.
canvasto canvas. -
Replace the drawing buffer of context.
-
Return context.
Note: User agents should consider issuing
developer-visible warnings when
an ignored options argument is provided when calling getContext()
to get a WebGPU canvas context.
21.2. GPUCanvasContext
[Exposed =(Window ,Worker ),SecureContext ]interface {GPUCanvasContext readonly attribute (HTMLCanvasElement or OffscreenCanvas )canvas ;undefined configure (GPUCanvasConfiguration configuration );undefined unconfigure ();GPUCanvasConfiguration ?getConfiguration ();GPUTexture getCurrentTexture (); };
GPUCanvasContext
has the following content timeline properties:
canvas, of type(HTMLCanvasElement or OffscreenCanvas), readonly-
The canvas this context was created from.
[[configuration]], of typeGPUCanvasConfiguration?, initiallynull-
The options this context is currently configured with.
nullif the context has not been configured or has beenunconfigured. [[textureDescriptor]], of typeGPUTextureDescriptor?, initiallynull-
The currently configured texture descriptor, derived from the
[[configuration]]and canvas.nullif the context has not been configured or has beenunconfigured. [[drawingBuffer]], an image, initially a transparent black image with the same size as the canvas-
The drawing buffer is the working-copy image data of the canvas. It is exposed as writable by
[[currentTexture]](returned bygetCurrentTexture()).The drawing buffer is used to get a copy of the image contents of a context, which occurs when the canvas is displayed or otherwise read. It may be transparent, even if
[[configuration]].alphaModeis"opaque". ThealphaModeonly affects the result of the "get a copy of the image contents of a context" algorithm.The drawing buffer outlives the
[[currentTexture]]and contains the previously-rendered contents even after the canvas has been presented. It is only cleared in Replace the drawing buffer.Any time the drawing buffer is read, implementations must ensure that all previously submitted work (e.g. queue submissions) have completed writing to it via
[[currentTexture]]. [[currentTexture]], of typeGPUTexture?, initiallynull-
The
GPUTextureto draw into for the current frame. It exposes a writable view onto the underlying[[drawingBuffer]].getCurrentTexture()populates this slot ifnull, then returns it.In the steady-state of a visible canvas, any changes to the drawing buffer made through the currentTexture get presented when updating the rendering of a WebGPU canvas. At or before that point, the texture is also destroyed and
[[currentTexture]]is set to tonull, signalling that a new one is to be created by the next call togetCurrentTexture().Destroyingthe currentTexture has no effect on the drawing buffer contents; it only terminates write-access to the drawing buffer early. During the same frame,getCurrentTexture()continues returning the same destroyed texture.Expire the current texture sets the currentTexture to
null. It is called byconfigure(), resizing the canvas, presentation,transferToImageBitmap(), and others. [[lastPresentedImage]], of type(readonly image)?, initiallynull-
The image most recently presented for this canvas in "updating the rendering of a WebGPU canvas". If the device is lost or destroyed, this image may be used as a fallback in "get a copy of the image contents of a context" in order to prevent the canvas from going blank.
Note: This property only needs to exist in implementations which implement the fallback, which is optional.
GPUCanvasContext
has the following methods:
configure(configuration)-
Configures the context for this canvas. This clears the drawing buffer to transparent black (in Replace the drawing buffer).
Called on:GPUCanvasContextthis.Arguments:
Arguments for the GPUCanvasContext.configure(configuration) method. Parameter Type Nullable Optional Description configurationGPUCanvasConfiguration✘ ✘ Desired configuration for the context. Returns: undefined
Content timeline steps:
-
Let device be configuration.
device. -
? Validate texture format required features of configuration.
formatwith device.[[device]]. -
? Validate texture format required features of each element of configuration.
viewFormatswith device.[[device]]. -
If Supported context formats does not contain configuration.
format, throw aTypeError. -
Let descriptor be the GPUTextureDescriptor for the canvas and configuration(this.
canvas, configuration). -
Set this.
[[configuration]]to configuration.NOTE:This spec requires supporting HDR via thetoneMappingoption. If a user agent only supportstoneMapping: "standard", then thetoneMappingmember should not exist inGPUCanvasConfiguration, so it will not exist on the object returned bygetConfiguration()and will not be accessed byconfigure()). This allows websites to detect feature support. -
Set this.
[[textureDescriptor]]to descriptor. -
Replace the drawing buffer of this.
-
Issue the subsequent steps on the Device timeline of device.
Device timeline steps:-
If any of the following requirements are unmet, generate a validation error and return.
-
validating GPUTextureDescriptor(device, descriptor) must return true.
Note: This early validation remains valid until the next
configure()call, except for validation of thesize, which changes when the canvas is resized. -
-
unconfigure()-
Removes the context configuration. Destroys any textures produced while configured.
Called on:GPUCanvasContextthis.Returns: undefined
Content timeline steps:
-
Set this.
[[configuration]]tonull. -
Set this.
[[textureDescriptor]]tonull. -
Replace the drawing buffer of this.
-
getConfiguration()-
Returns the context configuration.
Called on:GPUCanvasContextthis.Returns:
GPUCanvasConfigurationornullContent timeline steps:
-
Let configuration be a copy of this.
[[configuration]]. -
Return configuration.
NOTE:In scenarios wheregetConfiguration()shows thattoneMappingis implemented and the dynamic-range media query indicates HDR support, then WebGPU canvas should render content using the full HDR range instead of clamping values to the SDR range of the HDR display. -
getCurrentTexture()-
Get the
GPUTexturethat will be composited to the document by theGPUCanvasContextnext.NOTE:An application should callgetCurrentTexture()in the same task that renders to the canvas texture. Otherwise, the texture could get destroyed by these steps before the application is finished rendering to it.The expiry task (defined below) is optional to implement. Even if implemented, task source priority is not normatively defined, so may happen as early as the next task, or as late as after all other task sources are empty (see automatic expiry task source). Expiry is only guaranteed when a visible canvas is displayed (updating the rendering of a WebGPU canvas) and in other callers of "Expire the current texture".
Called on:GPUCanvasContextthis.Returns:
GPUTextureContent timeline steps:
-
If this.
[[configuration]]isnull, throw anInvalidStateErrorand return. -
Assert this.
[[textureDescriptor]]is notnull. -
Let device be this.
[[configuration]].device. -
If this.
[[currentTexture]]isnull:-
Replace the drawing buffer of this.
-
Set this.
[[currentTexture]]to the result of calling device.createTexture()with this.[[textureDescriptor]], except with theGPUTexture’s underlying storage pointing to this.[[drawingBuffer]].Note: If the texture can’t be created (e.g. due to validation failure or out-of-memory), this generates and error and returns an invalidated
GPUTexture. Some validation here is redundant with that done inconfigure(). Implementations must not skip this redundant validation.
-
-
Optionally, queue an automatic expiry task with device device and the following steps:
-
Expire the current texture of this.
Note: If this already happened when updating the rendering of a WebGPU canvas, it has no effect.
-
-
Return this.
[[currentTexture]].
Note: The same
GPUTextureobject will be returned by every call togetCurrentTexture()until "Expire the current texture" runs, even if thatGPUTextureis destroyed, failed validation, or failed to allocate. -
Arguments:
-
context: the
GPUCanvasContext
Returns: image contents
Content timeline steps:
-
Let snapshot be a transparent black image of the same size as context.
canvas. -
Let configuration be context.
[[configuration]]. -
If configuration is
null:-
Return snapshot.
Note: The configuration will be
nullif the context has not been configured or has beenunconfigured. This is identical to the behavior when the canvas has no context. -
-
Ensure that all submitted work items (e.g. queue submissions) have completed writing to the image (via context.
[[currentTexture]]). -
If configuration.
deviceis found to be valid:-
Set snapshot to a copy of the context.
[[drawingBuffer]].
Else, if context.
[[lastPresentedImage]]is notnull:-
Optionally, set snapshot to a copy of context.
[[lastPresentedImage]].Note: This is optional because the
[[lastPresentedImage]]may no longer exist, depending on what caused device loss. Implementations may choose to skip it even if do they still have access to that image.
-
-
Let alphaMode be configuration.
alphaMode. -
- If alphaMode is
"opaque": -
-
Clear the alpha channel of snapshot to 1.0.
-
Tag snapshot as being opaque.
Note: If the
[[currentTexture]], if any, has been destroyed (for example in "Expire the current texture"), the alpha channel is unobservable, and implementations may clear the alpha channel in-place. -
- Otherwise:
-
Tag snapshot with alphaMode.
- If alphaMode is
-
Tag snapshot with the
colorSpaceandtoneMappingof configuration. -
Return snapshot.
GPUCanvasContext
context, run
the following content
timeline steps:
-
Expire the current texture of context.
-
Let configuration be context.
[[configuration]]. -
Set context.
[[drawingBuffer]]to a transparent black image of the same size as context.canvas.-
If configuration is null, the drawing buffer is tagged with the color space
"srgb". In this case, the drawing buffer will remain blank until the context is configured. -
If not, the drawing buffer has the specified configuration.
formatand is tagged with the specified configuration.colorSpaceand configuration.toneMapping.
Note: configuration.
alphaModeis ignored until "get a copy of the image contents of a context".NOTE:A newly replaced drawing buffer image behaves as if it is cleared to transparent black, but, like after"discard", an implementation can clear it lazily only if it becomes necessary.Note: This will often be a no-op, if the drawing buffer is already cleared and has the correct configuration.
-
GPUCanvasContext
context, run
the following content
timeline steps:
-
If context.
[[currentTexture]]is notnull:-
Call context.
[[currentTexture]].destroy()(without destroying context.[[drawingBuffer]]) to terminate write access to the image. -
Set context.
[[currentTexture]]tonull.
-
21.3. HTML Specification Hooks
The following algorithms "hook" into algorithms in the HTML specification, and must run at the specified points.
HTMLCanvasElement
or OffscreenCanvas
with a
GPUCanvasContext
context, run the following content timeline steps:
-
Return a copy of the image contents of context.
-
When an
HTMLCanvasElementhas its rendering updated.-
Including when the canvas is the placeholder canvas element of an
OffscreenCanvas.
-
-
When
transferToImageBitmap()creates anImageBitmapfrom the bitmap. (See also transferToImageBitmap from WebGPU.) -
When WebGPU canvas contents are read using other Web APIs, like
drawImage(),texImage2D(),texSubImage2D(),toDataURL(),toBlob(), and so on.
If alphaMode
is "opaque",
this incurs a clear of the alpha channel. Implementations may skip this step when
they are able to read or display images in a way that ignores the alpha channel.
If an application needs a canvas only for interop (not presentation), avoid
"opaque"
if it is not needed.
HTMLCanvasElement
or an OffscreenCanvas
with a placeholder canvas element)
with a GPUCanvasContext
context, which occurs before getting the canvas’s image contents,
in the following sub-steps of the event loop processing model:
-
"update the rendering or user interface of that
Document" -
"update the rendering of that dedicated worker"
Note:
Service and Shared workers do not have "update the rendering" steps
because they cannot render to user-visible canvases.
requestAnimationFrame()
is not exposed in
ServiceWorkerGlobalScope
and SharedWorkerGlobalScope,
and
OffscreenCanvases
from transferControlToOffscreen()
cannot be sent to these workers.
Run the following content timeline steps:
-
Expire the current texture of context.
Note: If this already happened in the task queued by
getCurrentTexture(), it has no effect. -
Set context.
[[lastPresentedImage]]to context.[[drawingBuffer]].Note: This is just a reference, not a copy; the drawing buffer’s contents can’t change in-place after the current texture has expired.
Note:
This does not happen for standalone OffscreenCanvases
(created by new OffscreenCanvas()).
When transferToImageBitmap()
is called on a canvas with
GPUCanvasContext
context, after creating an ImageBitmap
from the canvas’s bitmap,
run the following content timeline steps:
-
Replace the drawing buffer of context.
Note: This makes transferToImageBitmap()
equivalent to "moving" (and possibly alpha-clearing) the image contents into the
ImageBitmap, without a copy.
-
The update the canvas size algorithm.
21.4. GPUCanvasConfiguration
The supported
context formats are the set of GPUTextureFormats:
«"bgra8unorm",
"rgba8unorm",
"rgba16float"».
These formats must be supported when specified as a
GPUCanvasConfiguration.format
regardless of the given
GPUCanvasConfiguration.device.
Note: Canvas configuration cannot use srgb
formats like "bgra8unorm-srgb".
Instead, use the non-srgb equivalent ("bgra8unorm"),
specify the srgb
format in the viewFormats,
and use createView()
to create
a view with an srgb format.
enum GPUCanvasAlphaMode {"opaque" ,"premultiplied" , };enum GPUCanvasToneMappingMode {"standard" ,"extended" , };dictionary {GPUCanvasToneMapping GPUCanvasToneMappingMode = "standard"; };mode dictionary {GPUCanvasConfiguration required GPUDevice device ;required GPUTextureFormat format ;GPUTextureUsageFlags usage = 0x10; // GPUTextureUsage.RENDER_ATTACHMENTsequence <GPUTextureFormat >viewFormats = [];PredefinedColorSpace colorSpace = "srgb";GPUCanvasToneMapping toneMapping = {};GPUCanvasAlphaMode alphaMode = "opaque"; };
GPUCanvasConfiguration
has the following members:
device, of type GPUDevice-
The
GPUDevicethat textures returned bygetCurrentTexture()will be compatible with. format, of type GPUTextureFormat-
The format that textures returned by
getCurrentTexture()will have. Must be one of the Supported context formats. usage, of type GPUTextureUsageFlags, defaulting to0x10-
The usage that textures returned by
getCurrentTexture()will have.RENDER_ATTACHMENTis the default, but is not automatically included if the usage is explicitly set. Be sure to includeRENDER_ATTACHMENTwhen setting a custom usage if you wish to use textures returned bygetCurrentTexture()as color targets for a render pass. viewFormats, of type sequence<GPUTextureFormat>, defaulting to[]-
The formats that views created from textures returned by
getCurrentTexture()may use. colorSpace, of type PredefinedColorSpace, defaulting to"srgb"-
The color space that values written into textures returned by
getCurrentTexture()should be displayed with. toneMapping, of type GPUCanvasToneMapping, defaulting to{}-
The tone mapping determines how the content of textures returned by
getCurrentTexture()are to be displayed.Note: If an implementation doesn’t support HDR WebGPU canvases, it should also not expose this member, to allow for feature detection. See
getConfiguration(). alphaMode, of type GPUCanvasAlphaMode, defaulting to"opaque"-
Determines the effect that alpha values will have on the content of textures returned by
getCurrentTexture()when read, displayed, or used as an image source.
GPUCanvasContext
to be used with a specific GPUDevice,
using the preferred
format for this context:
const canvas= document. createElement( 'canvas' ); const context= canvas. getContext( 'webgpu' ); context. configure({ device: gpuDevice, format: navigator. gpu. getPreferredCanvasFormat(), });
HTMLCanvasElement
or OffscreenCanvas)
canvas,
GPUCanvasConfiguration
configuration)
is a GPUTextureDescriptor
with the following members:
-
size: [canvas.width, canvas.height, 1]. -
viewFormats: configuration.viewFormats.
and other members set to their defaults.
canvas.width refers to HTMLCanvasElement.width
or OffscreenCanvas.width.
canvas.height refers to HTMLCanvasElement.height
or OffscreenCanvas.height.
21.4.1. Canvas Color Space
During presentation, the color values in the canvas are converted to the color space of the screen.
The toneMapping
determines the handling of values
outside of the [0, 1] interval in the color space of the screen.
21.4.2. Canvas Context sizing
All canvas configuration is set in configure()
except for the resolution
of the canvas, which is set by the canvas’s width and height.
Note: Like WebGL and 2d canvas, resizing a WebGPU canvas loses the current contents of the drawing buffer. In WebGPU, it does so by replacing the drawing buffer.
HTMLCanvasElement
or OffscreenCanvas
canvas with a
GPUCanvasContext
context has its width or height attributes set,
update the canvas size by running the following
content timeline
steps:
-
Replace the drawing buffer of context.
-
Let configuration be context.
[[configuration]] -
If configuration is not
null:-
Set context.
[[textureDescriptor]]to the GPUTextureDescriptor for the canvas and configuration(canvas, configuration).
-
Note: This may result in a GPUTextureDescriptor
which exceeds the
maxTextureDimension2D
of the device. In this case,
validation will fail inside getCurrentTexture().
Note: This algorithm is run any time the
canvas width or height attributes are set, even
if their value is not changed.
21.5. GPUCanvasToneMappingMode
This enum specifies how color values are displayed to the screen.
"standard"-
Color values within the standard dynamic range of the screen are unchanged, and all other color values are projected to the standard dynamic range of the screen.
Note: This projection is often accomplished by clamping color values in the color space of the screen to the
[0, 1]interval.For example, suppose that the value(1.035, -0.175, -0.140)is written to an'srgb'canvas.If this is presented to an sRGB screen, then this will be converted to sRGB (which is a no-op, because the canvas is sRGB), then projected into the display’s space. Using component-wise clamping, this results in the sRGB value
(1.0, 0.0, 0.0).If this is presented to a Display P3 screen, then this will be converted to the value
(0.948, 0.106, 0.01)in the Display P3 color space, and no clamping will be needed. "extended"-
Color values in the extended dynamic range of the screen are unchanged, and all other color values are projected to the extended dynamic range of the screen.
Note: This projection is often accomplished by clamping color values in the color space of the screen to the interval of values that the screen is capable of displaying, which may include values greater than
1.For example, suppose that the value(2.5, -0.15, -0.15)is written to an'srgb'canvas.If this is presented to an sRGB screen that is capable of displaying values in the
[0, 4]interval in sRGB space, then this will be converted to sRGB (which is a no-op, because the canvas is sRGB), then projected into the display’s space. If using component-wise clamping, this results in the sRGB value(2.5, 0.0, 0.0).If this is presented to a Display P3 screen that is capable of displaying values in the
[0, 2]interval in Display P3 space, then this will be converted to the value(2.3, 0.545, 0.386)in the Display P3 color space, then projected into the display’s space. If using component-wise clamping, this results in the Display P3 value(2.0, 0.545, 0.386).
21.6. GPUCanvasAlphaMode
This enum selects how the contents of the canvas will be interpreted when read, when displayed to the screen or used as an image source (in drawImage, toDataURL, etc.)
Below, src is a value in the canvas texture, and dst is an image that the canvas
is being composited into (e.g. an HTML page rendering, or a 2D canvas).
"opaque"-
Read RGB as opaque and ignore alpha values. If the content is not already opaque, the alpha channel is cleared to 1.0 in "get a copy of the image contents of a context".
"premultiplied"-
Read RGBA as premultiplied: color values are premultiplied by their alpha value. 100% red at 50% alpha is
[0.5, 0, 0, 0.5].If the canvas texture contains out-of-gamut premultiplied RGBA values at the time the canvas contents are read, the behavior depends on whether the canvas is:
- used as an image source
-
Values are preserved, as described in color space conversion.
- displayed to the screen
-
Compositing results are undefined.
Note: This is true even if color space conversion would produce in-gamut values before compositing, because the intermediate format for compositing is not specified.
22. Errors & Debugging
During the normal course of operation of WebGPU, errors are raised via dispatch error.
After a device is lost, errors are no longer surfaced, where possible. After this point, implementations do not need to run validation or error tracking:
-
The validity of objects on the device becomes unobservable.
-
popErrorScope()anduncapturederrorstop reporting errors. (No errors are generated by the device loss itself. Instead, theGPUDevice.lostpromise resolves to indicate the device is lost.) -
All operations which send a message back to the content timeline will skip their usual steps. Most will appear to succeed, except for
mapAsync(), which produces an error because it is impossible to provide the correct mapped data after the device has been lost.This makes it unobservable whether other types of operations (that don’t send messages back) actually execute or not.
22.1. Fatal Errors
enum {GPUDeviceLostReason ,"unknown" , }; ["destroyed" Exposed =(Window ,Worker ),SecureContext ]interface {GPUDeviceLostInfo readonly attribute GPUDeviceLostReason ;reason readonly attribute DOMString ; };message partial interface GPUDevice {readonly attribute Promise <GPUDeviceLostInfo >lost ; };
GPUDevice has
the following additional attributes:
lost, of type Promise<GPUDeviceLostInfo>, readonly-
A slot-backed attribute holding a promise which is created with the device, remains pending for the lifetime of the device, then resolves when the device is lost.
Upon initialization, it is set to a new promise.
22.2. GPUError
[Exposed =(Window ,Worker ),SecureContext ]interface GPUError {readonly attribute DOMString message ; };
GPUError is the
base interface for all errors surfaced from popErrorScope()
and the uncapturederror
event.
Errors must only be generated for operations that explicitly state the conditions one may be generated under in their respective algorithms, and the subtype of error that is generated.
No errors are generated from a device which is lost. See § 22 Errors & Debugging.
Note: GPUError may gain
new subtypes in future versions of this spec. Applications should handle
this possibility, using only the error’s message
when possible, and specializing using
instanceof. Use error.constructor.name when it’s necessary to serialize an error
(e.g. into
JSON, for a debug report).
GPUError has the
following immutable
properties:
message, of type DOMString, readonly-
A human-readable, localizable text message providing information about the error that occurred.
Note: This message is generally intended for application developers to debug their applications and capture information for debug reports, not to be surfaced to end-users.
Note: User agents should not include potentially machine-parsable details in this message, such as free system memory on
"out-of-memory"or other details about the conditions under which memory was exhausted.Note: The
messageshould follow the best practices for language and direction information. This includes making use of any future standards which may emerge regarding the reporting of string language and direction metadata.Editorial note: At the time of this writing, no language/direction recommendation is available that provides compatibility and consistency with legacy APIs, but when there is, adopt it formally.
[Exposed =(Window ,Worker ),SecureContext ]interface :GPUValidationError GPUError {(constructor DOMString ); };message
GPUValidationError
is a subtype of GPUError which
indicates that an operation did not
satisfy all validation requirements. Validation errors are always indicative of an application
error, and is expected to fail the same way across all devices assuming the same
[[features]]
and [[limits]]
are in use.
GPUDevice
device, run the following steps:
Device timeline steps:
-
Let error be a new
GPUValidationErrorwith an appropriate error message. -
Dispatch error error to device.
[Exposed =(Window ,Worker ),SecureContext ]interface :GPUOutOfMemoryError GPUError {(constructor DOMString ); };message
GPUOutOfMemoryError
is a subtype of GPUError which
indicates that there was not enough free
memory to complete the requested operation. The operation may succeed if attempted again with a
lower memory requirement (like using smaller texture dimensions), or if memory used by other
resources is released first.
GPUDevice
device, run the following steps:
Device timeline steps:
-
Let error be a new
GPUOutOfMemoryErrorwith an appropriate error message. -
Dispatch error error to device.
[Exposed =(Window ,Worker ),SecureContext ]interface :GPUInternalError GPUError {(constructor DOMString ); };message
GPUInternalError
is a subtype of GPUError which
indicates than an operation failed for a
system or implementation-specific reason even when all validation requirements have been satisfied.
For example, the operation may exceed the capabilities of the implementation in a way not easily
captured by the supported
limits. The same operation may succeed on other devices or under
difference circumstances.
GPUDevice
device, run the following steps:
Device timeline steps:
-
Let error be a new
GPUInternalErrorwith an appropriate error message. -
Dispatch error error to device.
22.3. Error Scopes
A GPU error scope
captures GPUErrors that
were generated while the
GPU error scope was
current. Error scopes are used to isolate errors that occur within a set
of WebGPU calls, typically for debugging purposes or to make an operation more fault tolerant.
GPU error scope has the following device timeline properties:
[[errors]], of type list<GPUError>, initially []-
The
GPUErrors, if any, observed while the GPU error scope was current. [[filter]], of typeGPUErrorFilter-
Determines what type of
GPUErrorthis GPU error scope observes.
enum {GPUErrorFilter "validation" ,"out-of-memory" ,"internal" , };partial interface GPUDevice {undefined pushErrorScope (GPUErrorFilter filter );Promise <GPUError ?>popErrorScope (); };
GPUErrorFilter
defines the type of errors that should be caught when calling
pushErrorScope():
"validation"-
Indicates that the error scope will catch a
GPUValidationError. "out-of-memory"-
Indicates that the error scope will catch a
GPUOutOfMemoryError. "internal"-
Indicates that the error scope will catch a
GPUInternalError.
GPUDevice has
the following device timeline properties:
[[errorScopeStack]], of type stack<GPU error scope>-
A stack of GPU error scopes that have been pushed to the
GPUDevice.
GPUError
error and GPUDevice
device is determined by issuing the following steps to the device timeline of device:
Device timeline steps:
-
If error is an instance of:
GPUValidationError-
Let type be "validation".
GPUOutOfMemoryError-
Let type be "out-of-memory".
GPUInternalError-
Let type be "internal".
-
Let scope be the last item of device.
[[errorScopeStack]]. -
While scope is not
undefined:-
If scope.
[[filter]]is type, return scope. -
Set scope to the previous item of device.
[[errorScopeStack]].
-
-
Return
undefined.
GPUError
error on GPUDevice
device, run the following device timeline steps:
Note: No errors are generated from a device which is lost. If this algorithm is called while device is lost, it will not be observable to the application. See § 22 Errors & Debugging.
-
Let scope be the current error scope for error and device.
-
If scope is not
undefined:-
Append error to scope.
[[errors]]. -
Return.
-
-
Otherwise issue the following steps to the content timeline:
-
If the user agent chooses, queue a global task for GPUDevice device with the following steps:
-
Fire a
GPUUncapturedErrorEventnamed "uncapturederror" on device, with anerrorof error.
-
Note: After dispatching the event, user agents
should surface uncaptured errors to
developers, for example as warnings in the browser’s developer console, unless the event’s
defaultPrevented
is true. In other words, calling preventDefault()
on the event should silence the console warning.
Note: The user agent may choose to throttle or limit
the number of GPUUncapturedErrorEvents
that a GPUDevice
can raise to prevent an excessive amount of error handling or logging from
impacting performance.
pushErrorScope(filter)-
Pushes a new GPU error scope onto the
[[errorScopeStack]]for this.Called on:GPUDevicethis.Arguments:
Arguments for the GPUDevice.pushErrorScope(filter) method. Parameter Type Nullable Optional Description filterGPUErrorFilter✘ ✘ Which class of errors this error scope observes. Returns:
undefinedContent timeline steps:
-
Issue the subsequent steps on the Device timeline of this.
Device timeline steps:-
Let scope be a new GPU error scope.
-
Set scope.
[[filter]]to filter. -
Push scope onto this.
[[errorScopeStack]].
-
popErrorScope()-
Pops a GPU error scope off the
[[errorScopeStack]]for this and resolves to anyGPUErrorobserved by the error scope, ornullif none.There is no guarantee of the ordering of promise resolution.
Called on:GPUDevicethis.Content timeline steps:
-
Let contentTimeline be the current Content timeline.
-
Let promise be a new promise.
-
Issue the check steps on the Device timeline of this.
-
Return promise.
Device timeline check steps:-
If this is lost:
-
Issue the following steps on contentTimeline:
Content timeline steps:-
Resolve promise with
null.
-
-
Return.
Note: No errors are generated from a device which is lost. See § 22 Errors & Debugging.
-
-
If any of the following requirements are unmet:
-
this.
[[errorScopeStack]].size must be > 0.
Then issue the following steps on contentTimeline and return:
Content timeline steps:-
Reject promise with an
OperationError.
-
-
Let scope be the result of popping an item off of this.
[[errorScopeStack]]. -
Let error be any one of the items in scope.
[[errors]], ornullif there are none.For any two errors E1 and E2 in the list, if E2 was caused by E1, E2 should not be the one selected.
Note: For example, if E1 comes from
t=createTexture(), and E2 comes fromt.createView()becausetwas invalid, E1 should be be preferred since it will be easier for a developer to understand what went wrong. Since both of these areGPUValidationErrors, the only difference will be in themessagefield, which is meant only to be read by humans anyway. -
At an unspecified point now or in the future, issue the subsequent steps on contentTimeline.
Note: By allowing
popErrorScope()calls to resolve in any order, with any of the errors observed by the scope, this spec allows validation to complete out of order, as long as any state observations are made at the appropriate point in adherence to this spec. For example, this allows implementations to perform shader compilation, which depends only on non-stateful inputs, to be completed on a background thread in parallel with other device-timeline work, and report any resulting errors later.
Content timeline steps:-
Resolve promise with error.
-
GPUDevice
operation that may fail:
gpuDevice. pushErrorScope( 'validation' ); let sampler= gpuDevice. createSampler({ maxAnisotropy: 0 , // Invalid, maxAnisotropy must be at least 1. }); gpuDevice. popErrorScope(). then(( error) => { if ( error) { // There was an error creating the sampler, so discard it. sampler= null ; console. error( `An error occured while creating sampler: ${ error. message} ` ); } });
For example: An error scope that only contains the creation of a single resource, such as a texture or buffer, can be used to detect failures such as out of memory conditions, in which case the application may try freeing some resources and trying the allocation again.
Error scopes do not identify which command failed, however. So, for instance, wrapping all the commands executed while loading a model in a single error scope will not offer enough granularity to determine if the issue was due to memory constraints. As a result freeing resources would usually not be a productive response to a failure of that scope. A more appropriate response would be to allow the application to fall back to a different model or produce a warning that the model could not be loaded. If responding to memory constraints is desired, the operations allocating memory can always be wrapped in a smaller nested error scope.
22.4. Telemetry
When a GPUError
is generated that is not observed by any GPU error scope, the user agent may fire an event named uncapturederror at a GPUDevice
using GPUUncapturedErrorEvent.
Note: uncapturederror
events are intended to be used for telemetry and reporting
unexpected errors. They may not be dispatched for all uncaptured errors (for example, there may be a limit
on the number of errors surfaced), and should not be used for handling known error cases that may occur
during
normal operation of an application. Prefer using pushErrorScope()
and
popErrorScope()
in those cases.
[Exposed =(Window ,Worker ),SecureContext ]interface :GPUUncapturedErrorEvent Event {(constructor DOMString ,type GPUUncapturedErrorEventInit ); [gpuUncapturedErrorEventInitDict SameObject ]readonly attribute GPUError error ; };dictionary :GPUUncapturedErrorEventInit EventInit {required GPUError ; };error
GPUUncapturedErrorEvent
has the following attributes:
error, of type GPUError, readonly-
A slot-backed attribute holding an object representing the error that was uncaptured. This has the same type as errors returned by
popErrorScope().
partial interface GPUDevice {attribute EventHandler onuncapturederror ; };
GPUDevice has
the following content timeline properties:
onuncapturederror, of type EventHandler-
An event handler IDL attribute for the
uncapturederrorevent type.
GPUDevice:
gpuDevice. addEventListener( 'uncapturederror' , ( event) => { // Re-surface the error, because adding an event listener may silence console logs. console. error( 'A WebGPU error was not captured:' , event. error); myEngineDebugReport. uncapturedErrors. push({ type: event. error. constructor . name, message: event. error. message, }); });
23. Detailed Operations
This section describes the details of various GPU operations.
23.1. Computing
Computing operations provide direct access to GPU’s programmable hardware.
Compute shaders do not have shader stage inputs or outputs; their results are
side effects from writing data into storage bindings bound either as
GPUBufferBindingLayout
with GPUBufferBindingType
"storage"
or as GPUStorageTextureBindingLayout.
These operations are encoded within GPUComputePassEncoder
as:
The main compute algorithm:
Arguments:
-
descriptor: Description of the current
GPUComputePipeline. -
dispatchCall: The dispatch call parameters. May come from function arguments or an
INDIRECTbuffer.
-
Let computeStage be descriptor.
compute. -
Let workgroupSize be the computed workgroup size for computeStage.
entryPointafter applying computeStage.constantsto computeStage.module. -
For workgroupX in range
[0, dispatchCall.:workgroupCountX]-
For workgroupY in range
[0, dispatchCall.:workgroupCountY]-
For workgroupZ in range
[0, dispatchCall.:workgroupCountZ]-
For localX in range
[0, workgroupSize.:x]-
For localY in range
[0, workgroupSize.:y]-
For localZ in range
[0, workgroupSize.:y]-
Let invocation be
{ computeStage, workgroupX, workgroupY, workgroupZ, localX, localY, localZ } -
Append invocation to computeInvocations.
-
-
-
-
-
-
-
For every invocation in computeInvocations, in any order the device chooses, including in parallel:
-
Set the shader builtins:
-
Set the num_workgroups builtin, if any, to
(
dispatchCall.workgroupCountX,
dispatchCall.workgroupCountY,
dispatchCall.workgroupCountZ
) -
Set the workgroup_id builtin, if any, to
(
invocation.workgroupX,
invocation.workgroupY,
invocation.workgroupZ
) -
Set the local_invocation_id builtin, if any, to
(
invocation.localX,
invocation.localY,
invocation.localZ
) -
Set the global_invocation_id builtin, if any, to
(.
invocation.workgroupX * workgroupSize.x+ invocation.localX,
invocation.workgroupY * workgroupSize.y+ invocation.localY,
invocation.workgroupZ * workgroupSize.z+ invocation.localZ
) -
Set the local_invocation_index builtin, if any, to
invocation.localX + (invocation.localY * workgroupSize.x) + (invocation.localZ * workgroupSize.x* workgroupSize.y)
-
-
Invoke the compute shader entry point described by invocation.computeStage.
-
Note: Shader invocations have no guaranteed order, and will generally run in parallel according to device capabilities. Developers should not assume that any given invocation or workgroup will complete before any other one is started. Some devices may appear to execute in a consistent order, but this behavior should not be relied on as it will not perform identically across all devices. Shaders that require synchronization across invocations must use Synchronization Built-in Functions to coordinate execution.
The device may become lost if shader execution does not end in a reasonable amount of time, as determined by the user agent.
23.2. Rendering
Rendering is done by a set of GPU operations that are executed within GPURenderPassEncoder,
and result in modifications of the texture data, viewed by the render pass attachments.
These operations are encoded with:
Note: rendering is the traditional use of GPUs, and is supported by multiple fixed-function blocks in hardware.
The main rendering algorithm:
Arguments:
-
pipeline: The current
GPURenderPipeline. -
drawCall: The draw call parameters. May come from function arguments or an
INDIRECTbuffer. -
state: RenderState of the
GPURenderCommandsMixinwhere the draw call is issued.
-
Let descriptor be pipeline.
[[descriptor]]. -
Resolve indices. See § 23.2.1 Index Resolution.
Let vertexList be the result of resolve indices(drawCall, state).
-
Process vertices. See § 23.2.2 Vertex Processing.
Execute process vertices(vertexList, drawCall, descriptor.
vertex, state). -
Assemble primitives. See § 23.2.3 Primitive Assembly.
Execute assemble primitives(vertexList, drawCall, descriptor.
primitive). -
Clip primitives. See § 23.2.4 Primitive Clipping.
Let primitiveList be the result of this stage.
-
Rasterize. See § 23.2.5 Rasterization.
Let rasterizationList be the result of rasterize(primitiveList, state).
-
Process fragments. See § 23.2.6 Fragment Processing.
Gather a list of fragments, resulting from executing process fragment(rasterPoint, descriptor, state) for each rasterPoint in rasterizationList.
-
Write pixels. See § 23.2.7 Output Merging.
For each non-null fragment of fragments:
-
Execute process depth stencil(fragment, pipeline, state).
-
Execute process color attachments(fragment, pipeline, state).
-
23.2.1. Index Resolution
At the first stage of rendering, the pipeline builds a list of vertices to process for each instance.
Arguments:
-
drawCall: The draw call parameters. May come from function arguments or an
INDIRECTbuffer. -
state: The snapshot of the
GPURenderCommandsMixinstate at the time of the draw call.
Returns: list of integer indices.
-
Let vertexIndexList be an empty list of indices.
-
If drawCall is an indexed draw call:
-
Initialize the vertexIndexList with drawCall.indexCount integers.
-
For i in range 0 .. drawCall.indexCount (non-inclusive):
-
Let relativeVertexIndex be fetch index(i + drawCall.
firstIndex, state.[[index_buffer]]). -
If relativeVertexIndex has the special value
"out of bounds", return the empty list.Note: Implementations may choose to display a warning when this occurs, especially when it is easy to detect (like in non-indirect indexed draw calls).
-
Append drawCall.
baseVertex+ relativeVertexIndex to the vertexIndexList.
-
-
-
Otherwise:
-
Initialize the vertexIndexList with drawCall.vertexCount integers.
-
Set each vertexIndexList item i to the value drawCall.firstVertex + i.
-
-
Return vertexIndexList.
Note: in the case of indirect draw calls, the
indexCount, vertexCount,
and other properties of drawCall are read from the indirect buffer
instead of the draw command itself.
Arguments:
-
i: Index of a vertex index to fetch.
-
state: The snapshot of the
GPURenderCommandsMixinstate at the time of the draw call.
Returns: unsigned integer or "out of bounds"
-
Let indexSize be defined by the state.
[[index_format]]: -
If state.
[[index_buffer_offset]]+ |i + 1| × indexSize > state.[[index_buffer_size]], return the special value"out of bounds". -
Interpret the data in state.
[[index_buffer]], starting at offset state.[[index_buffer_offset]]+ i × indexSize, of size indexSize bytes, as an unsigned integer and return it.
23.2.2. Vertex Processing
Vertex processing stage is a programmable stage of the render pipeline that processes the vertex attribute data, and produces clip space positions for § 23.2.4 Primitive Clipping, as well as other data for the § 23.2.6 Fragment Processing.
Arguments:
-
vertexIndexList: List of vertex indices to process (mutable, passed by reference).
-
drawCall: The draw call parameters. May come from function arguments or an
INDIRECTbuffer. -
desc: The descriptor of type
GPUVertexState. -
state: The snapshot of the
GPURenderCommandsMixinstate at the time of the draw call.
Each vertex vertexIndex in the vertexIndexList,
in each instance of index rawInstanceIndex, is processed independently.
The rawInstanceIndex is in range from 0 to drawCall.instanceCount - 1, inclusive.
This processing happens in parallel, and any side effects, such as
writes into GPUBufferBindingType
"storage"
bindings,
may happen in any order.
-
Let instanceIndex be rawInstanceIndex + drawCall.firstInstance.
-
For each non-
nullvertexBufferLayout in the list of desc.buffers:-
Let i be the index of the buffer layout in this list.
-
Let vertexBuffer, vertexBufferOffset, and vertexBufferBindingSize be the buffer, offset, and size at slot i of state.
[[vertex_buffers]]. -
Let vertexElementIndex be dependent on vertexBufferLayout.
stepMode:"vertex"-
vertexIndex
"instance"-
instanceIndex
-
Let drawCallOutOfBounds be
false. -
For each attributeDesc in vertexBufferLayout.
attributes:-
Let attributeOffset be vertexBufferOffset + vertexElementIndex * vertexBufferLayout.
arrayStride+ attributeDesc.offset. -
If attributeOffset + byteSize(attributeDesc.
format) > vertexBufferOffset + vertexBufferBindingSize:-
Set drawCallOutOfBounds to
true. -
Optionally (implementation-defined), empty vertexIndexList and return, cancelling the draw call.
Note: This allows implementations to detect out-of-bounds values in the index buffer before issuing a draw call, instead of using invalid memory reference behavior.
-
-
-
For each attributeDesc in vertexBufferLayout.
attributes:-
If drawCallOutOfBounds is
true:-
Load the attribute data according to WGSL’s invalid memory reference behavior, from vertexBuffer.
Note: Invalid memory reference allows several behaviors, including actually loading the "correct" result for an attribute that is in-bounds, even when the draw-call-wide drawCallOutOfBounds is
true.
Otherwise:
-
Let attributeOffset be vertexBufferOffset + vertexElementIndex * vertexBufferLayout.
arrayStride+ attributeDesc.offset. -
Load the attribute data of format attributeDesc.
formatfrom vertexBuffer starting at offset attributeOffset. The components are loaded in the orderx,y,z,wfrom buffer memory.
-
-
Convert the data into a shader-visible format, according to channel formats rules.
An attribute of type"snorm8x2"and byte values of[0x70, 0xD0]will be converted tovec2<f32>(0.88, -0.38)in WGSL. -
Adjust the data size to the shader type:
-
if both are scalar, or both are vectors of the same dimensionality, no adjustment is needed.
-
if data is vector but the shader type is scalar, then only the first component is extracted.
-
if both are vectors, and data has a higher dimension, the extra components are dropped.
An attribute of type"float32x3"and valuevec3<f32>(1.0, 2.0, 3.0)will exposed to the shader asvec2<f32>(1.0, 2.0)if a 2-component vector is expected. -
if the shader type is a vector of higher dimensionality, or the data is a scalar, then the missing components are filled from
vec4<*>(0, 0, 0, 1)value.An attribute of type"sint32"and value5will be exposed to the shader asvec4<i32>(5, 0, 0, 1)if a 4-component vector is expected.
-
-
Bind the data to vertex shader input location attributeDesc.
shaderLocation.
-
-
-
For each
GPUBindGroupgroup at index in state.[[bind_groups]]:-
For each resource
GPUBindingResourcein the bind group:-
Let entry be the corresponding
GPUBindGroupLayoutEntryfor this resource. -
If entry.
visibilityincludesVERTEX:-
Bind the resource to the shader under group index and binding
GPUBindGroupLayoutEntry.binding.
-
-
-
-
Set the shader builtins:
-
Set the
vertex_indexbuiltin, if any, to vertexIndex. -
Set the
instance_indexbuiltin, if any, to instanceIndex.
-
-
Invoke the vertex shader entry point described by desc.
Note: The target platform caches the results of vertex shader invocations. There is no guarantee that any vertexIndex that repeats more than once will result in multiple invocations. Similarly, there is no guarantee that a single vertexIndex will only be processed once.
The device may become lost if shader execution does not end in a reasonable amount of time, as determined by the user agent.
23.2.3. Primitive Assembly
Primitives are assembled by a fixed-function stage of GPUs.
Arguments:
-
vertexIndexList: List of vertex indices to process.
-
drawCall: The draw call parameters. May come from function arguments or an
INDIRECTbuffer. -
desc: The descriptor of type
GPUPrimitiveState.
For each instance, the primitives get assembled from the vertices that have been processed by the shaders, based on the vertexIndexList.
-
First, if the primitive topology is a strip, (which means that desc.
stripIndexFormatis not undefined) and the drawCall is indexed, the vertexIndexList is split into sub-lists using the maximum value of desc.stripIndexFormatas a separator.Example: a vertexIndexList with values
[1, 2, 65535, 4, 5, 6]of type"uint16"will be split in sub-lists[1, 2]and[4, 5, 6]. -
For each of the sub-lists vl, primitive generation is done according to the desc.
topology:"line-list"-
Line primitives are composed from (vl.0, vl.1), then (vl.2, vl.3), then (vl.4 to vl.5), etc. Each subsequent primitive takes 2 vertices.
"line-strip"-
Line primitives are composed from (vl.0, vl.1), then (vl.1, vl.2), then (vl.2, vl.3), etc. Each subsequent primitive takes 1 vertex.
"triangle-list"-
Triangle primitives are composed from (vl.0, vl.1, vl.2), then (vl.3, vl.4, vl.5), then (vl.6, vl.7, vl.8), etc. Each subsequent primitive takes 3 vertices.
"triangle-strip"-
Triangle primitives are composed from (vl.0, vl.1, vl.2), then (vl.2, vl.1, vl.3), then (vl.2, vl.3, vl.4), then (vl.4, vl.3, vl.5), etc. Each subsequent primitive takes 1 vertices.
Any incomplete primitives are dropped.
23.2.4. Primitive Clipping
Vertex shaders have to produce a built-in position (of type vec4<f32>),
which denotes the clip
position of a vertex in clip space coordinates.
Primitives are clipped to the clip volume, which, for any clip position p inside a primitive, is defined by the following inequalities:
-
−p.w ≤ p.x ≤ p.w
-
−p.w ≤ p.y ≤ p.w
-
0 ≤ p.z ≤ p.w (depth clipping)
When the "clip-distances"
feature is enabled, this clip
volume can
be further restricted by user-defined half-spaces by declaring clip_distances in the
output of vertex stage. Each value in the clip_distances array will be linearly
interpolated across the primitive, and the portion of the primitive with interpolated distances less
than 0 will be clipped.
If descriptor.primitive.unclippedDepth
is true,
depth clipping is not
applied: the clip volume is not
bounded in the z dimension.
A primitive passes through this stage unchanged if every one of its edges
lie entirely inside the clip
volume.
If the edges of a primitives intersect the boundary of the clip volume,
the intersecting edges are reconnected by new edges that lie along the boundary of the clip volume.
For triangular primitives (descriptor.primitive.topology
is
"triangle-list"
or "triangle-strip"),
this reconnection
may result in introduction of new vertices into the polygon, internally.
If a primitive intersects an edge of the clip volume’s boundary, the clipped polygon must include a point on this boundary edge.
If the vertex shader outputs other floating-point values (scalars and vectors), qualified with "perspective" interpolation, they also get clipped. The output values associated with a vertex that lies within the clip volume are unaffected by clipping. If a primitive is clipped, however, the output values assigned to vertices produced by clipping are clipped.
Considering an edge between vertices a and b that got clipped, resulting in the vertex c, let’s define t to be the ratio between the edge vertices: c.p = t × a.p + (1 − t) × b.p, where x.p is the output clip position of a vertex x.
For each vertex output value "v" with a corresponding fragment input, a.v and b.v would be the outputs for a and b vertices respectively. The clipped shader output c.v is produced based on the interpolation qualifier:
- flat
-
Flat interpolation is unaffected, and is based on the provoking vertex, which is determined by the interpolation sampling mode declared in the shader. The output value is the same for the whole primitive, and matches the vertex output of the provoking vertex.
- linear
-
The interpolation ratio gets adjusted against the perspective coordinates of the clip positions, so that the result of interpolation is linear in screen space.
- perspective
-
The value is linearly interpolated in clip space, producing perspective-correct values.
The result of primitive clipping is a new set of primitives, which are contained within the clip volume.
23.2.5. Rasterization
Rasterization is the hardware processing stage that maps the generated primitives
to the 2-dimensional rendering area of the framebuffer -
the set of render attachments in the current GPURenderPassEncoder.
This rendering area is split into an even grid of pixels.
The framebuffer coordinates start from the top-left corner of the render targets. Each unit corresponds exactly to one pixel. See § 3.3 Coordinate Systems for more information.
Rasterization determines the set of pixels affected by a primitive. In case of multi-sampling,
each pixel is further split into
descriptor.multisample.count
samples.
The standard sample
patterns are as follows,
with positions in framebuffer coordinates relative to the top-left corner of the pixel,
such that the pixel ranges from (0, 0) to (1, 1):
multisample.count
| Sample positions |
|---|---|
| 1 | Sample 0: (0.5, 0.5) |
| 4 |
Sample 0: (0.375, 0.125) Sample 1: (0.875, 0.375) Sample 2: (0.125, 0.625) Sample 3: (0.625, 0.875) |
Implementations must use the standard sample pattern for the given
multisample.count
when performing rasterization.
Let’s define a FragmentDestination to contain:
- position
-
the 2D pixel position using framebuffer coordinates
- sampleIndex
-
an integer in case § 23.2.10 Per-Sample Shading is active, or
nullotherwise
We’ll also use a notion of normalized device coordinates, or NDC. In this coordinate system, the viewport bounds range in X and Y from -1 to 1, and in Z from 0 to 1.
Rasterization produces a list of RasterizationPoints, each containing the following data:
- destination
-
refers to FragmentDestination
- coverageMask
-
refers to multisample coverage mask (see § 23.2.11 Sample Masking)
- frontFacing
-
is true if it’s a point on the front face of a primitive
- perspectiveDivisor
-
refers to interpolated 1.0 ÷ W across the primitive
- depth
-
refers to the depth in viewport coordinates, i.e. between the
[[viewport]]minDepthandmaxDepth. - primitiveVertices
-
refers to the list of vertex outputs forming the primitive
- barycentricCoordinates
-
refers to § 23.2.5.3 Barycentric coordinates
Arguments:
-
primitiveList: List of primitives to rasterize.
-
state: The active RenderState.
Returns: list of RasterizationPoint.
Each primitive in primitiveList is processed independently. However, the order of primitives affects later stages, such as depth/stencil operations and pixel writes.
-
First, the clipped vertices are transformed into NDC - normalized device coordinates. Given the output position p, the NDC position and perspective divisor are:
ndc(p) = vector(p.x ÷ p.w, p.y ÷ p.w, p.z ÷ p.w)
divisor(p) = 1.0 ÷ p.w
-
Let vp be state.
[[viewport]]. Map the NDC position n into viewport coordinates:-
Compute framebuffer coordinates from the render target offset and size:
framebufferCoords(n) = vector(vp.
x+ 0.5 × (n.x + 1) × vp.width, vp.y+ 0.5 × (−n.y + 1) × vp.height) -
Compute depth by linearly mapping [0,1] to the viewport depth range:
depth(n) = vp.
minDepth+ n.z× ( vp.maxDepth- vp.minDepth)
-
-
Let rasterizationPoints be the list of points, each having its attributes (
divisor(p),framebufferCoords(n),depth(n), etc.) interpolated according to its position on the primitive, using the same interpolation as § 23.2.4 Primitive Clipping. If the attribute is user-defined (not a built-in output value) then the interpolation type specified by the @interpolate WGSL attribute is used. -
Proceed with a specific rasterization algorithm, depending on
primitive.topology:"point-list"-
The point, if not filtered by § 23.2.4 Primitive Clipping, goes into § 23.2.5.1 Point Rasterization.
"line-list"or"line-strip"-
The line cut by § 23.2.4 Primitive Clipping goes into § 23.2.5.2 Line Rasterization.
"triangle-list"or"triangle-strip"-
The polygon produced in § 23.2.4 Primitive Clipping goes into § 23.2.5.4 Polygon Rasterization.
-
Remove all the points rp from rasterizationPoints that have rp.destination.position outside of state.
[[scissorRect]]. -
Return rasterizationPoints.
23.2.5.1. Point Rasterization
A single FragmentDestination is selected within the pixel containing the framebuffer coordinates of the point.
The coverage mask depends on multi-sampling mode:
- sample-frequency
-
coverageMask = 1 ≪
sampleIndex - pixel-frequency multi-sampling
-
coverageMask = 1 ≪ descriptor.
multisample.count− 1 - no multi-sampling
-
coverageMask = 1
23.2.5.2. Line Rasterization
The exact algorithm used for line rasterization is not defined, and may differ between implementations. For example, the line may be drawn using § 23.2.5.4 Polygon Rasterization of a 1px-width rectangle around the line segment, or using Bresenham’s line algorithm to select the FragmentDestinations.
Note: See Basic Line Segment Rasterization and Bresenham Line Segment Rasterization in the Vulkan 1.3 spec for more details of how line these line rasterization algorithms may be implemented.
23.2.5.3. Barycentric coordinates
Barycentric coordinates is a list of n numbers bi, defined for a point p inside a convex polygon with n vertices vi in framebuffer space. Each bi is in range 0 to 1, inclusive, and represents the proximity to vertex vi. Their sum is always constant:
∑ (bi) = 1
These coordinates uniquely specify any point p within the polygon (or on its boundary) as:
p = ∑ (bi × pi)
For a polygon with 3 vertices - a triangle, barycentric coordinates of any point p can be computed as follows:
Apolygon = A(v1, v2, v3) b1 = A(p, b2, b3) ÷ Apolygon b2 = A(b1, p, b3) ÷ Apolygon b3 = A(b1, b2, p) ÷ Apolygon
Where A(list of points) is the area of the polygon with the given set of vertices.
For polygons with more than 3 vertices, the exact algorithm is implementation-dependent. One of the possible implementations is to triangulate the polygon and compute the barycentrics of a point based on the triangle it falls into.
23.2.5.4. Polygon Rasterization
A polygon is front-facing if it’s oriented towards the projection. Otherwise, the polygon is back-facing.
Arguments:
Returns: list of RasterizationPoint.
-
Let rasterizationPoints be an empty list.
-
Let v(i) be the framebuffer coordinates for the clipped vertex number i (starting with 1) in a rasterized polygon of n vertices.
Note: this section uses the term "polygon" instead of a "triangle", since § 23.2.4 Primitive Clipping stage may have introduced additional vertices. This is non-observable by the application.
-
Determine if the polygon is front-facing, which depends on the sign of the area occupied by the polygon in framebuffer coordinates:
area = 0.5 × ((v1.x × vn.y − vn.x × v1.y) + ∑ (vi+1.x × vi.y − vi.x × vi+1.y))
The sign of area is interpreted based on the
primitive.frontFace:"ccw"-
area > 0 is considered front-facing, otherwise back-facing
"cw"-
area < 0 is considered front-facing, otherwise back-facing
-
Cull based on
primitive.cullMode:"none"-
All polygons pass this test.
"front"-
The front-facing polygons are discarded, and do not process in later stages of the render pipeline.
"back"-
The back-facing polygons are discarded.
-
Determine a set of fragments inside the polygon in framebuffer space - these are locations scheduled for the per-fragment operations. This operation is known as "point sampling". The logic is based on descriptor.
multisample:- disabled
-
Fragments are associated with pixel centers. That is, all the points with coordinates C, where fract(C) = vector2(0.5, 0.5) in the framebuffer space, enclosed into the polygon, are included. If a pixel center is on the edge of the polygon, whether or not it’s included is not defined.
Note: this becomes a subject of precision for the rasterizer.
- enabled
-
Each pixel is associated with descriptor.
multisample.countlocations, which are implementation-defined. The locations are ordered, and the list is the same for each pixel of the framebuffer. Each location corresponds to one fragment in the multisampled framebuffer.The rasterizer builds a mask of locations being hit inside each pixel and provides is as "sample-mask" built-in to the fragment shader.
-
For each produced fragment of type FragmentDestination:
-
Let rp be a new RasterizationPoint object
-
Compute the list b as § 23.2.5.3 Barycentric coordinates of that fragment. Set rp.barycentricCoordinates to b.
-
Let di be the depth value of vi.
-
Set rp.depth to ∑ (bi × di)
-
Append rp to rasterizationPoints.
-
-
Return rasterizationPoints.
23.2.6. Fragment Processing
The fragment processing stage is a programmable stage of the render pipeline that computes the fragment data (often a color) to be written into render targets.
This stage produces a Fragment for each RasterizationPoint:
-
destination refers to FragmentDestination.
-
frontFacing is true if it’s a fragment on the front face of a primitive.
-
coverageMask refers to multisample coverage mask (see § 23.2.11 Sample Masking).
-
depth refers to the depth in viewport coordinates, i.e. between the
[[viewport]]minDepthandmaxDepth. -
colors refers to the list of color values, one for each target in
colorAttachments. -
depthPassed is
trueif the fragment passed thedepthCompareoperation. -
stencilPassed is
trueif the fragment passed the stencilcompareoperation.
Arguments:
-
rp: The RasterizationPoint, produced by § 23.2.5 Rasterization.
-
descriptor: The descriptor of type
GPURenderPipelineDescriptor. -
state: The active RenderState.
Returns: Fragment or
null.
-
Let fragmentDesc be descriptor.
fragment. -
Let depthStencilDesc be descriptor.
depthStencil. -
Let fragment be a new Fragment object.
-
Set fragment.destination to rp.destination.
-
Set fragment.frontFacing to rp.frontFacing.
-
Set fragment.coverageMask to rp.coverageMask.
-
If
frag_depthbuiltin is not produced by the shader:-
Set fragment.depthPassed to the result of compare fragment(fragment.destination, fragment.depth, "depth", state.
[[depthStencilAttachment]], depthStencilDesc?.depthCompare).
-
-
Set stencilState to depthStencilDesc?.
stencilFrontif rp.frontFacing istrueand depthStencilDesc?.stencilBackotherwise. -
Set fragment.stencilPassed to the result of compare fragment(fragment.destination, state.
[[stencilReference]], "stencil", state.[[depthStencilAttachment]], stencilState?.compare). -
If fragmentDesc is not
null:-
If fragment.depthPassed is
false, thefrag_depthbuiltin is not produced by the shader entry point, and the shader entry point does not write to any storage bindings, the following steps may be skipped. -
Set the shader input builtins. For each non-composite argument of the entry point, annotated as a builtin, set its value based on the annotation:
position-
vec4<f32>(rp.destination.position, rp.depth, rp.perspectiveDivisor) front_facing-
rp.frontFacing
sample_indexsample_mask-
rp.coverageMask
-
For each user-specified shader stage input of the fragment stage:
-
Let value be the interpolated fragment input, based on rp.barycentricCoordinates, rp.primitiveVertices, and the interpolation qualifier on the input.
-
Set the corresponding fragment shader location input to value.
-
-
Invoke the fragment shader entry point described by fragmentDesc.
The device may become lost if shader execution does not end in a reasonable amount of time, as determined by the user agent.
-
If the fragment issued
discard, returnnull. -
Set fragment.colors to the user-specified shader stage output values from the shader.
-
Take the shader output builtins:
-
If
frag_depthbuiltin is produced by the shader as value:-
Let vp be state.
[[viewport]]. -
Set fragment.depth to clamp(value, vp.
minDepth, vp.maxDepth). -
Set fragment.depthPassed to the result of compare fragment(fragment.destination, fragment.depth, "depth", state.
[[depthStencilAttachment]], depthStencilDesc?.depthCompare).
-
-
-
If
sample_maskbuiltin is produced by the shader as value:-
Set fragment.coverageMask to fragment.coverageMask ∧ value.
-
Otherwise we are in § 23.2.8 No Color Output mode, and fragment.colors is empty.
-
-
Return fragment.
Arguments:
-
destination: The FragmentDestination.
-
value: The value to be compared.
-
aspect: The aspect of attachment to sample values from.
-
attachment: The attachment to be compared against.
-
compareFunc: The
GPUCompareFunctionto use, orundefined.
Returns: true if the comparison passes, or false otherwise
-
If attachment is
undefinedor does not have aspect, returntrue. -
If compareFunc is
undefinedor"always", returntrue. -
Let attachmentValue be the value of aspect of attachment at destination.
-
Return
trueif comparing value with attachmentValue using compareFunc succeeds, andfalseotherwise.
Processing of fragments happens in parallel, while any side effects,
such as writes into GPUBufferBindingType
"storage"
bindings,
may happen in any order.
23.2.7. Output Merging
Output merging is a fixed-function stage of the render pipeline that outputs the fragment color, depth and stencil data to be written into the render pass attachments.
Arguments:
-
fragment: The Fragment, produced by § 23.2.6 Fragment Processing.
-
pipeline: The current
GPURenderPipeline. -
state: The active RenderState.
-
Let depthStencilDesc be pipeline.
[[descriptor]].depthStencil. -
If pipeline.
[[writesDepth]]istrueand fragment.depthPassed istrue:-
Set the value of the depth aspect of state.
[[depthStencilAttachment]]at fragment.destination to fragment.depth.
-
-
If pipeline.
[[writesStencil]]is true:-
Set stencilState to depthStencilDesc.
stencilFrontif fragment.frontFacing istrueand depthStencilDesc.stencilBackotherwise. -
If fragment.stencilPassed is
false:-
Let stencilOp be stencilState.
failOp.
Else if fragment.depthPassed is
false:-
Let stencilOp be stencilState.
depthFailOp.
Else:
-
Let stencilOp be stencilState.
passOp.
-
-
Update the value of the stencil aspect of state.
[[depthStencilAttachment]]at fragment.destination by performing the operation described by stencilOp.
-
The depth input to this stage, if any, is clamped to the current [[viewport]]
depth
range (regardless of whether the fragment shader stage writes the frag_depth builtin).
Arguments:
-
fragment: The Fragment, produced by § 23.2.6 Fragment Processing.
-
pipeline: The current
GPURenderPipeline. -
state: The active RenderState.
-
If fragment.depthPassed is
falseor fragment.stencilPassed isfalse, return. -
Let targets be pipeline.
[[descriptor]].fragment.targets. -
For each attachment of state.
[[colorAttachments]]:-
Let color be the value from fragment.colors that corresponds with attachment.
-
Let targetDesc be the targets entry that corresponds with attachment.
-
If targetDesc.
blendis provided:-
Set the RGB components of color to the value computed by performing the operation described by colorBlend.
operationwith the values described by colorBlend.srcFactorand colorBlend.dstFactor. -
Set the alpha component of color to the value computed by performing the operation described by alphaBlend.
operationwith the values described by alphaBlend.srcFactorand alphaBlend.dstFactor.
-
Set the value of attachment at fragment.destination to color.
-
23.2.8. No Color Output
In no-color-output mode, pipeline does not produce any color attachment outputs.
The pipeline still performs rasterization and produces depth values based on the vertex position output. The depth testing and stencil operations can still be used.
23.2.9. Alpha to Coverage
In alpha-to-coverage mode, an additional alpha-to-coverage mask
of MSAA samples is generated based on the alpha component of the
fragment shader output value at @location(0).
The algorithm of producing the extra mask is platform-dependent and can vary for different pixels. It guarantees that:
-
if alpha ≤ 0.0, the result is 0x0
-
if alpha ≥ 1.0, the result is 0xFFFFFFFF
-
intermediate alpha values should result in a proportionate number of bits set to 1 in the mask. Some platforms may not guarantee that the number of bits set to 1 in the mask monotonically increases as alpha increases for a given pixel.
23.2.10. Per-Sample Shading
When rendering into multisampled render attachments, fragment shaders can be run once per-pixel or once
per-sample.
Fragment shaders must run once per-sample if either the sample_index builtin or sample interpolation sampling
is used and contributes to the shader output. Otherwise fragment shaders may run once
per-pixel with the result
broadcast out to each of the samples included in the final sample mask.
When using per-sample shading, the color output for sample N is produced by the fragment shader
execution
with sample_index == N for the current pixel.
23.2.11. Sample Masking
The final sample mask
for a pixel is computed as:
rasterization mask
& mask
& shader-output
mask.
Only the lower count
bits of the mask are considered.
If the least-significant bit at position N of the final sample mask has value of "0", the sample color outputs (corresponding to sample N) to all attachments of the fragment shader are discarded. Also, no depth test or stencil operations are executed on the relevant samples of the depth-stencil attachment.
The rasterization mask is produced by the rasterization stage, based on the shape of the rasterized polygon. The samples included in the shape get the relevant bits 1 in the mask.
The shader-output
mask takes the output value of "sample_mask" builtin
in the fragment shader.
If the builtin is not output from the fragment shader, and alphaToCoverageEnabled
is enabled, the shader-output mask becomes the alpha-to-coverage mask.
Otherwise, it defaults to 0xFFFFFFFF.
24. Type Definitions
typedef [EnforceRange ]unsigned long ;GPUBufferDynamicOffset typedef [EnforceRange ]unsigned long ;GPUStencilValue typedef [EnforceRange ]unsigned long ;GPUSampleMask typedef [EnforceRange ]long ;GPUDepthBias typedef [EnforceRange ]unsigned long long ;GPUSize64 typedef [EnforceRange ]unsigned long ;GPUIntegerCoordinate typedef [EnforceRange ]unsigned long ;GPUIndex32 typedef [EnforceRange ]unsigned long ;GPUSize32 typedef [EnforceRange ]long ;GPUSignedOffset32 typedef unsigned long long ;GPUSize64Out typedef unsigned long ;GPUIntegerCoordinateOut typedef unsigned long ;GPUSize32Out typedef unsigned long ;GPUFlagsConstant
24.1. Colors & Vectors
dictionary {GPUColorDict required double r ;required double g ;required double b ;required double a ; };typedef (sequence <double >or GPUColorDict );GPUColor
Note: double is large enough to precisely
hold 32-bit signed/unsigned
integers and single-precision floats.
r, of type double-
The red channel value.
g, of type double-
The green channel value.
b, of type double-
The blue channel value.
a, of type double-
The alpha channel value.
GPUColor
value color, depending on its type, the syntax:
-
color.r refers to either
GPUColorDict.ror the first item of the sequence (asserting there is such an item). -
color.g refers to either
GPUColorDict.gor the second item of the sequence (asserting there is such an item). -
color.b refers to either
GPUColorDict.bor the third item of the sequence (asserting there is such an item). -
color.a refers to either
GPUColorDict.aor the fourth item of the sequence (asserting there is such an item).
Arguments:
-
color: The
GPUColorto validate.
Returns: undefined
Content timeline steps:
dictionary {GPUOrigin2DDict GPUIntegerCoordinate = 0;x GPUIntegerCoordinate = 0; };y typedef (sequence <GPUIntegerCoordinate >or GPUOrigin2DDict );GPUOrigin2D
GPUOrigin2D
value origin, depending on its type, the syntax:
-
origin.x refers to either
GPUOrigin2DDict.xor the first item of the sequence (0 if not present). -
origin.y refers to either
GPUOrigin2DDict.yor the second item of the sequence (0 if not present).
Arguments:
-
origin: The
GPUOrigin2Dto validate.
Returns: undefined
Content timeline steps:
dictionary {GPUOrigin3DDict GPUIntegerCoordinate = 0;x GPUIntegerCoordinate = 0;y GPUIntegerCoordinate = 0; };z typedef (sequence <GPUIntegerCoordinate >or GPUOrigin3DDict );GPUOrigin3D
GPUOrigin3D
value origin, depending on its type, the syntax:
-
origin.x refers to either
GPUOrigin3DDict.xor the first item of the sequence (0 if not present). -
origin.y refers to either
GPUOrigin3DDict.yor the second item of the sequence (0 if not present). -
origin.z refers to either
GPUOrigin3DDict.zor the third item of the sequence (0 if not present).
Arguments:
-
origin: The
GPUOrigin3Dto validate.
Returns: undefined
Content timeline steps:
dictionary {GPUExtent3DDict required GPUIntegerCoordinate width ;GPUIntegerCoordinate height = 1;GPUIntegerCoordinate depthOrArrayLayers = 1; };typedef (sequence <GPUIntegerCoordinate >or GPUExtent3DDict );GPUExtent3D
width, of type GPUIntegerCoordinate-
The width of the extent.
height, of type GPUIntegerCoordinate, defaulting to1-
The height of the extent.
depthOrArrayLayers, of type GPUIntegerCoordinate, defaulting to1-
The depth of the extent or the number of array layers it contains. If used with a
GPUTexturewith aGPUTextureDimensionof"3d"defines the depth of the texture. If used with aGPUTexturewith aGPUTextureDimensionof"2d"defines the number of array layers in the texture.
GPUExtent3D
value extent, depending on its type, the syntax:
-
extent.width refers to either
GPUExtent3DDict.widthor the first item of the sequence (asserting there is such an item). -
extent.height refers to either
GPUExtent3DDict.heightor the second item of the sequence (1 if not present). -
extent.depthOrArrayLayers refers to either
GPUExtent3DDict.depthOrArrayLayersor the third item of the sequence (1 if not present).
Arguments:
-
extent: The
GPUExtent3Dto validate.
Returns: undefined
Content timeline steps:
-
Throw a
TypeErrorif:
25. Feature Index
25.1. "core-features-and-limits"
Allows all Core WebGPU features and limits to be used.
Note: This is currently available on all adapters and enabled automatically on all devices even if not requested.
25.2. "depth-clip-control"
Allows depth clipping to be disabled.
This feature adds the following optional API surfaces:
-
New
GPUPrimitiveStatedictionary members:
25.3. "depth32float-stencil8"
Allows for explicit creation of textures of format "depth32float-stencil8".
This feature adds the following optional API surfaces:
-
New
GPUTextureFormatenum values:
25.4. "texture-compression-bc"
Allows for explicit creation of textures of BC compressed formats which include the "S3TC", "RGTC", and "BPTC" formats. Only supports 2D textures.
Note: Adapters which support "texture-compression-bc"
do not
always support "texture-compression-bc-sliced-3d".
To use "texture-compression-bc-sliced-3d",
"texture-compression-bc"
must be enabled explicitly as this feature
does not enable the BC formats.
This feature adds the following optional API surfaces:
-
New
GPUTextureFormatenum values:
25.5. "texture-compression-bc-sliced-3d"
Allows the 3d
dimension for textures with BC compressed formats.
Note: Adapters which support "texture-compression-bc"
do not
always support "texture-compression-bc-sliced-3d".
To use "texture-compression-bc-sliced-3d",
"texture-compression-bc"
must be enabled explicitly as this feature
does not enable the BC formats.
This feature adds no optional API surfaces.
25.6. "texture-compression-etc2"
Allows for explicit creation of textures of ETC2 compressed formats. Only supports 2D textures.
This feature adds the following optional API surfaces:
-
New
GPUTextureFormatenum values:
25.7. "texture-compression-astc"
Allows for explicit creation of textures of ASTC compressed formats. Only supports 2D textures.
This feature adds the following optional API surfaces:
-
New
GPUTextureFormatenum values:
25.8. "texture-compression-astc-sliced-3d"
Allows the 3d
dimension for textures with ASTC compressed formats.
Note: Adapters which support "texture-compression-astc"
do not
always support "texture-compression-astc-sliced-3d".
To use "texture-compression-astc-sliced-3d",
"texture-compression-astc"
must be enabled explicitly as this feature
does not enable the ASTC formats.
This feature adds no optional API surfaces.
25.9. "timestamp-query"
Adds the ability to query timestamps from GPU command buffers. See § 20.4 Timestamp Query.
This feature adds the following optional API surfaces:
-
New
GPUQueryTypevalues: -
New
GPUComputePassDescriptormembers: -
New
GPURenderPassDescriptormembers:
25.10. "indirect-first-instance"
Allows the use of non-zero firstInstance values in indirect draw parameters and
indirect drawIndexed parameters.
This feature adds no optional API surfaces.
25.11.
"shader-f16"
Allows the use of the half-precision floating-point type f16 in WGSL.
This feature adds the following optional API surfaces:
-
New WGSL extensions:
25.12. "rg11b10ufloat-renderable"
Allows the RENDER_ATTACHMENT
usage on textures with format "rg11b10ufloat",
and also allows textures of that format to be blended, multisampled, and resolved.
This feature adds no optional API surfaces.
Enabling "texture-formats-tier1"
at device creation will also enable
"rg11b10ufloat-renderable".
25.13. "bgra8unorm-storage"
Allows the STORAGE_BINDING
usage on textures with format "bgra8unorm".
This feature adds no optional API surfaces.
25.14. "float32-filterable"
Makes textures with formats "r32float",
"rg32float",
and
"rgba32float"
filterable.
25.15. "float32-blendable"
Makes textures with formats "r32float",
"rg32float",
and
"rgba32float"
blendable.
25.16. "clip-distances"
Allows the use of clip_distances in WGSL.
This feature adds the following optional API surfaces:
-
New WGSL extensions:
25.17. "dual-source-blending"
Allows the use of blend_src in WGSL and simultaneously using both pixel shader
outputs
(@blend_src(0) and @blend_src(1)) as inputs to a blending operation with the
single color
attachment at location 0.
This feature adds the following optional API surfaces:
-
Allows the use of the below
GPUBlendFactors: -
New WGSL extensions:
25.18.
"subgroups"
Allows the use of the subgroup and quad operations in WGSL.
This feature adds no optional API surfaces, but the following entries of GPUAdapterInfo
expose real values whenever the feature is available on the adapter:
-
New WGSL extensions:
25.19. "texture-formats-tier1"
Supports the below new GPUTextureFormats
with the RENDER_ATTACHMENT,
blendable, multisampling
capabilities and the STORAGE_BINDING
capability
with the "read-only"
and "write-only"
GPUStorageTextureAccesses:
Allows the RENDER_ATTACHMENT,
blendable, multisampling
and resolve
capabilities on below GPUTextureFormats:
Allows the "read-only"
or "write-only"
GPUStorageTextureAccess
on below GPUTextureFormats:
Enabling "texture-formats-tier2"
at device creation will also enable
"texture-formats-tier1".
Enabling "texture-formats-tier1"
at device creation will also enable
"rg11b10ufloat-renderable".
25.20. "texture-formats-tier2"
Allows the "read-write"
GPUStorageTextureAccess
on below
GPUTextureFormats:
Enabling "texture-formats-tier2"
at device creation will also enable
"texture-formats-tier1".
26. Appendices
26.1. Texture Format Capabilities
26.1.1. Plain color formats
All supported plain color
formats support usages
COPY_SRC,
COPY_DST,
and
TEXTURE_BINDING,
and dimension "3d".
The RENDER_ATTACHMENT
and STORAGE_BINDING
columns
specify support for GPUTextureUsage.RENDER_ATTACHMENT
and GPUTextureUsage.STORAGE_BINDING
usage respectively.
The render
target pixel byte cost
and render
target component alignment
are used to validate the maxColorAttachmentBytesPerSample
limit.
Note: The texel block memory cost of each of these formats is the same as its texel block copy footprint.
26.1.2. Depth-stencil formats
A depth-or-stencil format is any format with depth and/or stencil aspects. A combined depth-stencil format is a depth-or-stencil format that has both depth and stencil aspects.
All depth-or-stencil formats support the COPY_SRC,
COPY_DST,
TEXTURE_BINDING,
and RENDER_ATTACHMENT
usages.
All of these formats support multisampling.
However, certain copy operations also restrict the source and destination formats, and none of
these formats support textures with "3d"
dimension.
Depth textures cannot be used with "filtering"
samplers, but can always
be used with "comparison"
samplers even if they use filtering.
| Format |
NOTE:
Texel block memory cost (Bytes)
| Aspect | GPUTextureSampleType
| Valid texel copy source | Valid texel copy destination | Texel block copy footprint (Bytes) | Aspect-specific format |
|---|---|---|---|---|---|---|---|
stencil8
| 1 − 4 | stencil | "uint"
| ✓ | 1 | stencil8
| |
depth16unorm
| 2 | depth | "depth",
"unfilterable-float"
| ✓ | 2 | depth16unorm
| |
depth24plus
| 4 | depth | "depth",
"unfilterable-float"
| ✗ | – | depth24plus
| |
depth24plus-stencil8
| 4 − 8 | depth | "depth",
"unfilterable-float"
| ✗ | – | depth24plus
| |
| stencil | "uint"
| ✓ | 1 | stencil8
| |||
depth32float
| 4 | depth | "depth",
"unfilterable-float"
| ✓ | ✗ | 4 | depth32float
|
depth32float-stencil8
| 5 − 8 | depth | "depth",
"unfilterable-float"
| ✓ | ✗ | 4 | depth32float
|
| stencil | "uint"
| ✓ | 1 | stencil8
| |||
24-bit depth refers to a 24-bit unsigned normalized depth format with a range from 0.0 to 1.0, which would be spelled "depth24unorm" if exposed.
26.1.2.1. Reading and Sampling Depth/Stencil Textures
It is possible to bind a depth-aspect GPUTextureView
to either a texture_depth_* binding or a binding with other non-depth 2d/cube texture types.
A stencil-aspect GPUTextureView
must be bound to a normal texture binding type.
The sampleType
in the GPUBindGroupLayout
must be "uint".
Reading or sampling the depth or stencil aspect of a texture behaves as if the texture contains
the values (V, X, X, X), where V is the actual depth or stencil value,
and each X is an implementation-defined unspecified value.
For depth-aspect bindings, the unspecified values are not visible through bindings with
texture_depth_* types.
tex with type texture_2d<f32>:
-
textureSample(tex, ...)will returnvec4<f32>(D, X, X, X). -
textureGather(0, tex, ...)will returnvec4<f32>(D1, D2, D3, D4). -
textureGather(2, tex, ...)will returnvec4<f32>(X1, X2, X3, X4)(a completely unspecified value).
Note:
Short of adding a new more constrained stencil sampler type (like depth), it’s infeasible for
implementations to efficiently paper over the driver differences for depth/stencil reads.
As this was not a portability pain point for WebGL, it’s not expected to be problematic in WebGPU.
In practice, expect either (V, V, V, V) or (V, 0, 0, 1) (where V is
the depth or stencil
value), depending on hardware.
26.1.2.2. Copying Depth/Stencil Textures
The depth aspects of depth32float formats
("depth32float"
and "depth32float-stencil8"
have a limited range.
As a result, copies into such textures are only valid from other textures of the same format.
The depth aspects of depth24plus formats
("depth24plus"
and "depth24plus-stencil8")
have opaque representations (implemented as either 24-bit depth or "depth32float").
As a result, depth-aspect texel
copies are not allowed with these formats.
-
All of these formats can be written in a render pass using a fragment shader that outputs depth values via the
frag_depthoutput. -
Textures with "depth24plus" formats can be read as shader textures, and written to a texture (as a render pass attachment) or buffer (via a storage buffer binding in a compute shader).
26.1.3. Packed formats
All packed texture formats support COPY_SRC,
COPY_DST,
and TEXTURE_BINDING
usages.
All of these formats are filterable.
None of these formats are renderable
or support multisampling.
A compressed format is any format with a block size greater than 1×1.
Note: The texel block memory cost of each of these formats is the same as its texel block copy footprint.